如何查询名称在Python列表中包含任何单词的模型?

发布于 2021-01-29 15:08:21

实现目标:

我想要名称属性包含列表中任何单词的所有对象。

我有:

list = ['word1','word2','word3']
ob_list = data.objects.filter( // What to write here ?  )
// or any other way to get the objects where any word in list is contained, in 
// the na-me attribute of data.

例如:

if name="this is word2": 然后应返回具有该名称的对象,因为word2在列表中。

请帮忙!

关注者
0
被浏览
74
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以使用Q对象来构造如下查询:

    from django.db.models import Q
    
    ob_list = data.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
    

    编辑:

    reduce(lambda x, y: x | y, [Q(name__contains=word) for word in list]))
    

    是一种奇特的写作方式

    Q(name__contains=list[0]) | Q(name__contains=list[1]) | ... | Q(name__contains=list[-1])
    

    您还可以使用显式的for循环来构造Q对象。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看