带LinkWidget的django_filters需要All来清除过滤器

时间:2013-06-11 13:41:57

标签: django django-filters

是否可以将“全部”链接添加到我的过滤器集中,就像在管理列表过滤器中一样? 目前我有这个代码工作正常,除了它没有'全部'链接,重置过滤器的某些选择。

在我的filters.py

class VersionFilter(FilterSet):
    version = AllValuesFilter(widget=widgets.LinkWidget)
    codename = AllValuesFilter(widget=widgets.LinkWidget)

    class Meta:
        model = Version
        fields = ['version', 'codename', 'libraries',]

    def __init__(self, *args, **kwargs):
        super(VersionFilter, self).__init__(*args, **kwargs)
        libraries = Library.objects.values_list('name', flat=True).distinct()
        library = ChoiceFilter(
            name = "libraries__name",
            choices = set([(s, s) for s in libraries]),
            widget = widgets.LinkWidget,
        )
        self.filters['libraries'] = library

在我的views.py

class VersionsListViewFilter(FilterView):
    context_object_name = 'versions_list'
    filterset_class = VersionFilter

1 个答案:

答案 0 :(得分:0)

只需在选项列表中插入空选项:

def __init__(self, *args, **kwargs):
    super(VersionFilter, self).__init__(*args, **kwargs)
    libraries = Library.objects.values_list('name', flat=True).distinct()
    CHOICES = [(s, s) for s in libraries]
    CHOICES.insert(0, ('', 'All Libraries'))
    library = ChoiceFilter(
        name = "libraries__name",
        choices = CHOICES,
        widget = widgets.LinkWidget,
    )
    self.filters['libraries'] = library