Django Filters Problem: How To Display All Results When The Filter Is Not Set

10 Sep · by Tim Kamanin · 2 min read

If a view extends django-filter's FilterView it may look similar to this:

from django_filters.views import FilterView
from .filters import JobFilter

class JobList(FilterView):
    model = Job
        paginate_by = 20
        filterset_class = JobFilter

JobFilter has a single filter field city that filters jobs by city and generate URL like /jobs/?city=London

Everything is good and filter works, BUT, if you go to /jobs/ without any filter parameters set you'll see NOTHING!

That's the default behavior served us by FilterView.

But what if we want to list all jobs when the parameters are not set (which is the obvious wish I think)?

It turns out it's as easy as setting the strict variable toFalse in the View class.

So let's change our code to:

from django_filters.views import FilterView
from .filters import JobFilter

class JobList(FilterView):
    model = Job
    paginate_by = 20
    filterset_class = JobFilter
    # We set strict mode to False
    strict = False

And we're good to go!

Unfortunately, it isn't described in the docs, so I spent some time figuring this one out. I hope I've saved you some time, let me know if that's the case.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments