如何查询名称在Python列表中包含任何单词的模型? [英] How to Query model where name contains any word in python list?

查看:84
本文介绍了如何查询名称在Python列表中包含任何单词的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要达到的目标:

我希望name属性包含列表中任何单词的所有对象.

I want all objects where name attribute contains any word from the list.

我有:

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

if name="this is word2": Then object with such a name should be returned since word2 is in the list.

请帮助!

推荐答案

您可以使用

You could use Q objects to constuct a query like this:

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

You could also use an explicit for loop to construct the Q object.

这篇关于如何查询名称在Python列表中包含任何单词的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆