views:

153

answers:

3

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?

A: 

Maybe the queryset can be a callable instead of a 'real' queryset object. This way, it can be generated dynamically. At least this works in Django Models for references to other models.

The callable can be a class method in you Model.

Ber
+2  A: 

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.

Dmitry Shevchenko
This works, but __init__ needs *args and **kw, not only **kw.Thanks a lot!
mdgart
A: 

If I understand your question correctly I believe you want to use the AllValuesFilter.

import django_tables

provider = django_filters.AllValuesFilter(
    widget=django_filters.widgets.LinkWidget)

More information is available here: http://github.com/alex/django-filter/blob/master/docs/ref/filters.txt#L77

AJ
AllValuesFilter doesn't work (http://pastebin.com/pmw7gaxj), the results filters are not "filtered" but it show all the choices, and the LinkWidget doesn't work properly (it show a list of numbers instead of the text of the choice).
mdgart