Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query when parameter is none django

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)?
like image 454
Brian D Avatar asked Aug 10 '11 06:08

Brian D


1 Answers

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 ycolumn 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)
like image 80
jazz Avatar answered Oct 04 '22 22:10

jazz