5

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)

1 Answer 1

16

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.