检查is_null以获取Django queryset过滤中的字段列表 [英] Check is_null for list of field in Django queryset filtering

查看:417
本文介绍了检查is_null以获取Django queryset过滤中的字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用以下字段创建模型:

I have create model with this fields:

field_1 , field_2, field_3, ... , field_n

我想过滤包含以下k个字段的所有对象:

And I want to filter all objects that these k fields:

field_1 , field_2, .... , field_k

这些对象不是 Null

我的答案错误:

我确实认为必须创建要在查询中设置的以下字段列表:

I did think that I must create this list of fields that I want to set in my query:

my_list = [`field_1` , `field_2`, .... , `field_k`]

并创建如下查询:

my_objects = Class.objects.filter([ (eval(field_name +"__isnull = False") )  for field_name in my_list ])

但这是错误的。 我该怎么做?

But it was wrong. How can I do that?

推荐答案

您使事情变得太复杂了,您不能使用字符串构造列表并将其传递给 filter(..),以希望它可以工作。此外, eval(..)不能那样工作,即使这样做,也将导致严重的安全风险。应该尽可能避免使用 eval(..) exec(..)设法向其中注入字符串,它们可以在服务器上运行任意代码,从而尝试转储数据库,等等。请参见此答案,用于更深入地分析为什么 评估是不良习惯

You make things too complicated, you can not construct a list with strings and pass it to filter(..) in the hope that it will work. Furthermore eval(..) does not work that way, and even if it did, it would result in severe security risks. eval(..) and exec(..) should be avoided as much as possible, since from the moment someone manages to "inject" a string into it, they can run arbitrary code on your server, and thus try to "dump the database", etc. See this answer for a more in-depth analysis on why "Eval is bad practice".

您可以构造一个字段名称列表(这样的字符串):

You can construct a list of fields names (so strings):

my_list = ['field_1', 'field_2', 'field_k']

然后我们可以构建字典并执行字典解包,像这样:

Then we can construct a dictionary and perform dictionary unpacking, like:

Class.objects.filter(**{'{}__isnull'.format(f): False for f in my_list})

两个星号( ** ),因此将进行函数调用,如 f(** {'a':4,'b':2}) f(a = 4,b = 2)相同,因此在这里可以我喜欢 .filter(field_1__isnull = False,field_2__isnull = False,field_k__isnull = False)

The two asterisks (**), will thus make a function call, such that f(**{'a': 4, 'b': 2}), is the same as f(a=4, b=2), and thus here it will make a call like .filter(field_1__isnull=False, field_2__isnull=False, field_k__isnull=False).

href = / questions / tagged / python-3.6 class = post-tag title =显示已标记'python-3.6' rel = tag> python-3.6 的问题,我们可以利用 f-strings

Or since python-3.6, we can make use of f-strings:

Class.objects.filter(**{f'{f}__isnull': False for f in my_list})

这篇关于检查is_null以获取Django queryset过滤中的字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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