在Django Admin中为list_filter创建自定义过滤器

在Django Admin中为list_filter创建自定义过滤器

确实可以通过扩展SimpleListFilter将自定义过滤器添加到管理过滤器。举例来说,如果你想为“非洲”加洲过滤器上面使用的国家管理过滤器,你可以做到以下几点:

在admin.py:

from django.contrib.admin import SimpleListFilter 

class CountryFilter(SimpleListFilter): 
    title = 'country' # or use _('country') for translated title 
    parameter_name = 'country' 

    def lookups(self, request, model_admin): 
     countries = set([c.country for c in model_admin.model.objects.all()]) 
     return [(c.id, c.name) for c in countries] + [ 
      ('AFRICA', 'AFRICA - ALL')] 

    def queryset(self, request, queryset): 
     if self.value() == 'AFRICA': 
      return queryset.filter(country__continent='Africa') 
     if self.value(): 
      return queryset.filter(country__id__exact=self.value()) 

class CityAdmin(ModelAdmin): 
    list_filter = (CountryFilter,) 

Last updated