Postgre SQL ignore the filtering condition if the value is null

会有一股神秘感。 提交于 2021-01-04 08:03:06

问题


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

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

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)

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)

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

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

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


回答1:


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)



回答2:


Initially, create your own Custom Model Manager

class MyManager(models.Manager):
    def custom_filter(self, *args, **kwargs):
        filtered_kwargs = {key: value for key, value in kwargs.items() if value}
        return super().filter(*args, **filtered_kwargs)

and then wire-up in your model as,

class MyModel(models.Model):
    objects = MyManager()
    # other model fields

Now, filter your queryset as,

queryset = User.objects.values().custom_filter(A_name=A, B_name=SomeNullValue)


来源:https://stackoverflow.com/questions/60332175/postgre-sql-ignore-the-filtering-condition-if-the-value-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!