2011-08-25 102 views
1

我需要過濾基於TextField的管理列表。我希望能夠爲其TextField值爲Null的所有對象過濾查詢集。Django Admin過濾列表通過TextField

我試過如下:

def filter_for_field(self, request, queryset): 

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

我補充說,我AdminModel的方法,然後添加屬性「行動= [‘filter_for_field’]

我也試着做沒有。 return語句,沒有骰子。該動作上顯示的是管理員,但它不與該文本字段爲空值刪除對象。

我在做什麼錯?

有沒有更好的方法來做到這一點?

回答

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,)