开发者

Hide filter items that produce zero results in django-filter

I have an issue with the djang开发者_如何学Pythono-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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜