In my viewSet I am doing a query,
queryset= Books.objects.all();
Now from an ajax call I get my filter values from UI i.e. age,gender, etc. of auther.There will be a total of 5 filters.
Now the problem which I ran into is how am I going to add filters to my query(only those filters which have any value).
What I tried is I checked for individual filter value and did query, but that way it fails as if the user remove the filter value or add multiple filters. Any better suggestion how to accomplish this?
You can simply get the request.GET content as a dict (making sure to convert the values to string or a desired type as they'd be list by default i.e:
dict(request.GET)
would give you something like{u'a': [u'val']}
.Once you are sure you have a dictionary of keys matching your model fields, you can simply do:
filtered = queryset.filter(**dict_container)
Here's a bit more generic one. It will apply filters to your queryset if they are passed as the
GET
parameters. If you're doing aPOST
call, just change the name in the code.Note that you can use lookup expressions in your filters' names. For example, if you want to filter books with price lower or equal to specified in filter, you could just use
price__lte
as a filter name.Maybe django-filter would help simplify the solutions others have given?
Something like:
Then the view looks like:
For more information see the documentation.
You haven't shown any code, so you haven't really explained what the problem is:
Start with the queryset
Book.objects.all()
. For each filter, check if there is a value for the filter inrequest.POST
, and if so, filter the queryset. Django querysets are lazy, so only the final queryset will be evaluated.