What is simplest way join __contains and __in?

匆匆过客 提交于 2020-01-21 17:26:13

问题


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)

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!


回答1:


Here you go:

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

A couple of tips:

  • You should be naming your model classes with a capital (i.e. Text, not text)
  • You may want __icontains instead if you're not worried about the case



回答2:


I don't know Django, so I have no idea how to apply this filter, but it seems you want a function like this one:

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)


来源:https://stackoverflow.com/questions/1732680/what-is-simplest-way-join-contains-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!