Django Admin过滤列表按TextField

时间:2011-08-25 19:28:47

标签: django django-models django-admin

我需要根据TextField过滤管理列表。我希望能够为TextField值为Null的所有对象筛选查询集。

我尝试了以下内容:

 def filter_for_field(self, request, queryset):

    queryset=queryset.exclude(field__isnull=True)
    return queryset

我添加了作为我的AdminModel的方法,然后添加了属性“actions = ['filter_for_field']。

我也尝试过没有返回声明,没有骰子。该操作显示在管理员中,但它不会删除TextField的空值对象。

我做错了什么?

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用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,)