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.
2
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:
- Keyword argument unpacking using the
**
operator with adict
:
my_filter = {
"field1": "foo"
"field2__gt": 10
}
if my_boolean:
my_filter["additional_field"] = "bar"
objects = MyModel.objects.filter(**my_filter)
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)
2
You can work with a Q
object to get to similar syntax, like:
from django.db.models import Q
objects = Class.objects.filter(Q(('field__lookup', value) if condition else ()))
although it thus does some wrapping. Perhaps a better way is just make a small helper function:
def qif(*args, _if=True, **kwargs):
if _condition:
return Q(*args, **kwargs)
return Q()
and use:
objects = Class.objects.filter(qif(field__lookup=value, _if=condition))
Note: It might be worth to take a look at
django-filter
[GitHub] to do filtering based on aQueryDict
in a more declarative way.
1