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

标签 python django list

目标实现:

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

我有:

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 在列表中。

请帮忙!

最佳答案

您可以使用 Q objects构造这样的查询:

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 对象。

关于python - 如何查询名称包含python列表中任何单词的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088173/

相关文章:

python - 在 Python 中给定一个奇数长度的值列表,我如何交换列表中除最终值之外的所有值?

python - 是否可以仅使用枕头库生成 gif 动画?

python - 采用 1 个位置参数,但给出了 2 个

python -/socket.io/* 404 未找到 flask

python - Django Admin 中的嵌套内联

django - 跨域 POST 请求的 CSRF 验证在生产中失败

python - 在 Python 3.x 中卸载模块(与重新加载不同)

ajax - Django 1.9 + django-cors-headers + AJAX 不工作

c# - XmlSerializer 序列化泛型接口(interface)列表

python - 如何使用 pandas 现有列之一中的列表创建新列,并从另一列的列表中分配值?