I want to make a query, something like
Model.objects.filter(x=x).filter(y=y).filter(z=z)
... but there are some cases when for example y
I do not know, if I get your question, but
Model.objects.filter(x=x, y__isnull = False, z=z)
gives you the queryset, where the y
column is non-null (IS NOT NULL
).
Here's the relevant documentation.
EDIT: Check if y is None and build your queryset dynamically:
if y is None:
qs = Model.objects.filter(x=x).filter(z=z)
elif z is None:
qs = Model.objects.filter(x=x).filter(y=y)
...
If there are too many arguments to deal with, you could use something like this; assuming that x
, y
, z
are stored in a dictionary your values
:
your_values = { 'x' : 'x value', 'y' : 'y value', 'z' : 'value'}
arguments = {}
for k, v in your_values.items():
if v:
arguments[k] = v
Model.objects.filter(**arguments)