djangodjango-database

Activate/deactivate filtering in django based on condition


I have a bool and if it is True, I want to filter in my query by some stuff, if not I don't want to filter.

At the moment my solution is this:

if my_boolean:
    objects = Class.objects.filter(argument=valuexyz, ...)
else:
    objects = Class.objects.filter(...)

My real query is much longer. I just used this for simplification. Now my questions is could I do this inline?

Like:

objects = Class.objects.filter( if my_boolean: argument=valuexyz; else: no_filtering)`

Is there a way to do it like this somehow? This would save me quite some redundant lines of code.


Solution

  • Your current method is fast and readable, given that there is only one boolean and only 2 possible queries. I would leave it as it is. That being said, if your actual use case is more complex, you can use:

    1. Keyword argument unpacking using the ** operator with a dict:
    my_filter = {
      "field1": "foo"
      "field2__gt": 10
    }
    if my_boolean:
        my_filter["additional_field"] = "bar"
    objects = MyModel.objects.filter(**my_filter)
    
    1. Q objects:
    my_q = Q(field1="foo", field2__gt=10)
    if my_boolean:
        my_q &= Q(additional_field="bar")
    objects = MyModel.objects.filter(my_q)