最简单的方法是加入__contains和__in? [英] What is simplest way join __contains and __in?
问题描述
我正在做标签搜索功能,用户可以观察很多标签,所有这一切都在一个元组中,现在我想从列表中找到至少包含一个标签的所有文本。
符号: text__contains__in =('asd','dsa')
我唯一的想法是做循环,例如: p>
I am doing tag search function, user could observe a lot of tags, I get it all in one tuple, and now I would like to find all text which include at least one tag from the list.
Symbolic: text__contains__in=('asd','dsa')
My only idea is do loop e.g.:
q = text.objects.all()
for t in tag_tuple:
q.filter(data__contains=t)
例如:
输入标签元组,('car','cat','cinema')
输出所有包含至少一个单词的消息,所以我的猫是在汽车中
,猫不允许在电影院
,我会把我的车开到电影院
感谢您的帮助!
For example:
input tuple of tags, ('car', 'cat', 'cinema')
output all messages what contains at least one word from that tuple, so My cat is in the car
, cat is not allowed in the cinema
, i will drive my car to the cinema
Thanks for help!
推荐答案
你去:
filter = Q()
for t in tag_tuple:
filter = filter | Q(data__contains=t)
return text.objects.filter(filter)
提示:
- 你应该用一个资本命名你的模型类(即
Text
,而不是文本
) - 您可能需要
__ icontains
不用担心这种情况
- You should be naming your model classes with a capital (i.e.
Text
, nottext
) - You may want
__icontains
instead if you're not worried about the case
这篇关于最简单的方法是加入__contains和__in?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!