如何从“全部”更改默认过滤器选择?我有一个名为领域status它有三个值:activate,pending和rejected。当我list_filter在Django admin中使用时,默认情况下将过滤器设置为“全部”,但默认情况下我想将其设置为待处理。
status
activate,pending
rejected
list_filter
class MyModelAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): if not request.GET.has_key('decommissioned__exact'): q = request.GET.copy() q['decommissioned__exact'] = 'N' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)
为了实现这一点,并在侧边栏中有一个可用的“全部”链接(即显示全部而不显示未决的链接),你需要创建一个自定义列表过滤器,django.contrib.admin.filters.SimpleListFilter默认情况下继承并过滤“待处理”。遵循这些原则的方法应该起作用:
django.contrib.admin.filters.SimpleListFilter
from datetime import date from django.utils.translation import ugettext_lazy as _ from django.contrib.admin import SimpleListFilter class StatusFilter(SimpleListFilter): title = _('Status') parameter_name = 'status' def lookups(self, request, model_admin): return ( (None, _('Pending')), ('activate', _('Activate')), ('rejected', _('Rejected')), ('all', _('All')), ) def choices(self, cl): for lookup, title in self.lookup_choices: yield { 'selected': self.value() == lookup, 'query_string': cl.get_query_string({ self.parameter_name: lookup, }, []), 'display': title, } def queryset(self, request, queryset): if self.value() in ('activate', 'rejected'): return queryset.filter(status=self.value()) elif self.value() == None: return queryset.filter(status='pending') class Admin(admin.ModelAdmin): list_filter = [StatusFilter]