如果该值为null,则Postgre SQL会忽略过滤条件 [英] Postgre SQL ignore the filtering condition if the value is null

查看:50
本文介绍了如果该值为null,则Postgre SQL会忽略过滤条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下三个变量传递给查询 A,B和C .

I have the following three variables passed to the query A,B and C.

A,B和C可以采用任何值,包括null.

A, B and C can take any values including null.

当我运行下面的查询集时,如果A,B或C中的值为空,它应该忽略条件

When I run the below queryset, it should ignore the condition if the value in A,B or C is null

queryset = User.objects.values().filter(A_name=A, B_name=B, C_name =C)

例如,如果C值传入null,则查询的行为应类似于

For example, if C value passed in null then the query should behave like

queryset = User.objects.values().filter(A_name=A, B_name=B)

如果C和A值传入null,则查询的行为应类似于

And if C and A value passed in null then the query should behave like

queryset = User.objects.values().filter(B_name=B)

我不想编写所有9种组合并编写查询.我有什么办法可以轻松做到吗?.

I dont want to write all the 9 combinations and write a query. Is there any way I can do it easily?.

推荐答案

您可以将参数保留为dict,并仅将不等于None的参数发送给filter()方法:

You can keep arguments as dict and send to filter() method only those of them which are not equal to None:

arguments = {"A_name": A, "B_name": B, "C_name": C}
arguments_without_null = {k: v for k, v in arguments.items() if v is not None}
queryset = User.objects.values().filter(**arguments_without_null)

这篇关于如果该值为null,则Postgre SQL会忽略过滤条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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