【问题标题】:What is simplest way join __contains and __in?加入 __contains 和 __in 的最简单方法是什么?
【发布时间】:2010-12-16 12:04:36
【问题描述】:

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

【问题讨论】:

  • 你能举一个输入和预期输出的例子吗?

标签: django django-queryset django-orm


【解决方案1】:

我不了解 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)

【讨论】:

    【解决方案2】:

    给你:

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

    几个提示:

    • 你应该用大写命名你的模型类(即Text,而不是text
    • 如果您不担心此案,您可能需要 __icontains 代替

    【讨论】:

    • 很高兴,如果它可以工作,看起来很简单,thx +1 和接受的答案:)
    猜你喜欢
    • 2010-10-06
    • 1970-01-01
    • 2010-10-06
    • 2019-07-06
    • 2015-11-26
    • 2011-05-09
    • 1970-01-01
    • 2014-07-05
    • 2019-04-21
    相关资源
    最近更新 更多