Skip to content Skip to sidebar Skip to footer

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

Solution 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)

Solution 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,

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

Now, filter your queryset as,

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

Post a Comment for "Postgre Sql Ignore The Filtering Condition If The Value Is Null"