Query when parameter is none django
A better approach on the otherwise very readable @rolling-stone answer:
models = Model.objects.all()
variables = {'x':x,'y':y,'z':z}
for key, value in variables.items():
if value is not None:
models = models.filter(**{key: value})
Anyway, depending on the specific filter, you'll need to apply filters together in the same .filter() call, so the "blind" way only works in the simple cases. See https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships for more information on those cases.
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)
Something like this could work:
models = Model.objects.all()
variables = {'x':'x','y':'y','z':'z'}
for key, value in variables.items():
if key=='x' and value:
models = models.filter(x=value)
if key=='y' and value:
models = models.filter(y=value)
if key=='z' and value:
models = models.filter(z=value)
Because QuerySets are lazy, this doesn't involve any database activity.