Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django objects.filter multiple filters

The user can select fields to filter by, I need to filter by only those fields but there can be 3 fields.

The user selects all three options:a, b and c

Foo.objects.filter(a=1,b=2,c=3), good

What if the user selects only 1 option or 2 options ?

Foo,objects.filter(a=1, b=2, c=not selected)

How can I do this to only filter by the selected choices. THis comes from a post to the view, and looks like this if not selected:

a=1,b=NaN,c=3

So b was not selected and I would not like to inlclude it in my filter,

Foo.objects.filter(a=1,c=3)

Or can I perhaps so a filter that is basically a "all" selector

So as per above:

Foo.objects.filter(a=1,b=%,c=3)
like image 200
Harry Avatar asked Dec 06 '22 19:12

Harry


1 Answers

You can use a keyword argument dict:

filterargs = { 'a': 1, 'b': 2, 'c': 3 }
Foo.objects.filter(**filterargs)

then to only filter on a and b:

filterargs = { 'a': 1, 'b': 2 }

or a and c:

filterargs = { 'a': 1, 'c': 3}
like image 120
John Keyes Avatar answered Dec 28 '22 16:12

John Keyes