gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:50:52 24 4
gpt4 key购买 nike

目标实现:

我想要 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com