2

我正在做标签搜索功能,用户可以观察到很多标签,我把它全部放在一个元组中,现在我想从列表中找到包含至少一个标签的所有文本。
象征性:text__contains__in=('asd','dsa')
我唯一的想法是循环,例如:

q = text.objects.all() 

for t in tag_tuple: 
   q.filter(data__contains=t)

例如:输入标签的元组,('car', 'cat', 'cinema') 输出包含该元组中至少一个单词的所有消息,所以,,My cat is in the car谢谢 帮助!cat is not allowed in the cinemai will drive my car to the cinema

4

2 回答 2

9

干得好:

filter = Q()
for t in tag_tuple: 
   filter = filter | Q(data__contains=t)
return text.objects.filter(filter)

几个提示:

  • 你应该用大写命名你的模型类(即Text,不是text
  • __icontains如果你不担心这个案子,你可能想要
于 2009-11-17T20:02:44.300 回答
0

我不知道 Django,所以我不知道如何应用这个过滤器,但似乎你想要一个这样的函数:

def contains_one_of(tags, text):
    text = text.split()   # tags should match complete words, not partial words
    return any(t in text for t in tags)
于 2009-11-14T13:06:51.523 回答