如何查询名称在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 个回答
-
您可以使用
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
对象。