当参数为none时查询 [英] Query when parameter is none django

查看:119
本文介绍了当参数为none时查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想进行查询,例如

Model.objects.filter(x=x).filter(y=y).filter(z=z) 

...但是在某些情况下,例如y为None.这会从字面上搜索数据库中y列中的空值-如果没有该查询参数,有一种从本质上忽略该查询参数的巧妙方法,即返回queryset

... but there are some cases when for example y is None. This literally searches the database for null values in the y column -- is there a nifty way to essentially disregard that query parameter if it is none, i.e. return the queryset

Model.objects.filter(x=x).filter(z=z)?

推荐答案

我不知道,如果我收到您的问题,但是

I do not know, if I get your question, but

Model.objects.filter(x=x, y__isnull = False, z=z)

为您提供查询集,其中y列为非空(IS NOT NULL).

gives you the queryset, where the ycolumn is non-null (IS NOT NULL).

此处是相关文档.

检查y是否为None并动态构建查询集:

Check if y is None and build your queryset dynamically:

if y is None:
    qs = Model.objects.filter(x=x).filter(z=z)
elif z is None:
    qs = Model.objects.filter(x=x).filter(y=y)
...

如果要处理的参数太多,则可以使用类似这样的方法;假设xyz存储在字典your values中:

If there are too many arguments to deal with, you could use something like this; assuming that x, y, z are stored in a dictionary your values:

your_values = { 'x' : 'x value', 'y' : 'y value', 'z' : 'value'}
arguments = {}
for k, v in your_values.items():
    if v:
        arguments[k] = v

Model.objects.filter(**arguments)

这篇关于当参数为none时查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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