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 is None. This literally searches the database for null values in the y column -- is there a nifty way to essentially disregard that query parameter if it is none, i.e. return the queryset
Model.objects.filter(x=x).filter(z=z)?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With