我正在做标签搜索功能,用户可以观察很多标签,我将所有标签都放在一个元组中,现在我想找到包含列表中至少一个标签的所有文本。
象征性: 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 cinema, i will drive my car to the cinema 感谢帮助!

有帮助吗?

解决方案

干得好:

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

一些提示:

  • 您应该使用大写字母来命名您的模型类(即 Text, , 不是 text)
  • 你可能想要 __icontains 相反,如果你不担心这个案子

其他提示

我不知道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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top