Django query to get all ads whose keyword sets are contained by a search string
I am trying to implement an advertising system in Django. My model for ads is as follows:
class Ad(models.Model):
...
campaign = models.ForeignKey(Campaign)
keyword = models.ManyToManyField(Keyword)
def keystring(self):
keys = self.keyword.all()
keystring_value = ""
for key in keys:
keystring_value = keystring_value + ke开发者_Python百科y.keyword_name
keystring_value = str(keystring_value)
return (keystring_value)
...
The relevant part here is the keyword attribute. It is a many to many relationship with a master list of keyword objects. So when a user searches for some set of keywords, say "keyword1 keyword2 keyword3", i want all ads with the following keyword sets to return: "keyword1 keyword2", "keyword2 keyword3", "keyword1", "keyword1 keyword2 keyword3", etc -- any ad whose keyword set is contained by the search string. I do NOT want that search to return an ad for "keyword1 keyword2 keyword3 keyword4". Any help would be greatly appreciated.
The easiest thing I can think of is to take the complement of your list of keywords -- that is, say after processing user input you have a list of strings like ['keyword1', 'keyword2', 'keyword3']
in a variable keywords
. Then you take all the keywords which are not in that list:
disallowed_keywords = Keyword.objects.exclude(keyword_name__in=keywords)
And then instead of finding ads that match your wanted keywords, you exclude those that match the wrong ones:
Ad.objects.exclude(keyword__in=disallowed_keywords)
精彩评论