Hide filter items that produce zero results in django-filter

django, django-filter, filter, python

Solution

Basically, you need to apply filters, and then apply them again, but on newly-generated queryset. Something like this:

f = SomeFilter(request.GET) 
f = SomeFilter(request.GET, queryset=f.qs)

Now when you have correct queryset, you can override providers dynamically in init:

def __init__(self, **kw):
   super(SomeFilter, self).__init__(**kw)
   self.filters['provider'].extra['queryset'] = Provider.objects.filter(foo__in=self.queryset)

Not pretty but it works. You should probably encapsulate those two calls into more-efficient method on filter.

Problem

I have an issue with the django-filter application: how to hide the items that will produce zero results. I think that there is a simple method to do this, but idk how. I'm using the LinkWidget on a ModelChoiceFilter, like this: ``` provider = django_filters.ModelChoiceFilter(queryset=Provider.objects.all(), widget=django_filters.widgets.LinkWidget) ``` What I need to do is filter the queryset and select only the Provider that will produce at least one result, and exclude the others. There is a way to do that?

Original source