srccode
srccode

Reputation: 751

Postgre SQL ignore the filtering condition if the value is null

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?.

Upvotes: 2

Views: 440

Answers (2)

JPG
JPG

Reputation: 88509

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)

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47354

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)

Upvotes: 1

Related Questions