您可以使用custom FilterSpec功能來創建自定義管理員過濾器。它現在在Django的SVN版本中可用,並計劃在Django 1.4。
from django.contrib.admin import SimpleListFilter
class IsNullFilter(SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('Custom filter')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'custom_filter'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (
('True', _('is Null')),
('False', _('is not Null')),
)
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value() == 'True':
return queryset.filter(costomfield__isnull=True)
if self.value() == 'True':
return queryset.filter(costomfield__isnull=False)
然後,你需要將它傳遞ModelAdmin.list_filter
:
class CustomModelAdmin(admin.ModelAdmin):
list_filter = (IsNullFilter,)