2011-08-25 3 views
1

TextField를 기반으로 관리 목록을 필터링해야합니다. TextField 값이 Null 인 모든 객체에 대해 쿼리 세트를 필터링 할 수 있기를 원합니다. .Django Admin Filtering List by TextField

def filter_for_field(self, request, queryset): 

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

내가 재산 "액션 = [ 'filter_for_field를'] 추가 내 AdminModel에 대한 방법으로 다음

내가도없이하려고 노력한다고 덧붙였다 :

나는 다음과 같은 시도 return 문, 아니 주사위. 동작은 관리자에 표시되어 있지만 텍스트 필드에 null 값으로 개체를 제거하지 않습니다.

내가 잘못 뭐하는 거지?

더 좋은 방법이 있나요?

답변

1

custom FilterSpec 기능을 사용하여 사용자 지정 관리 필터를 만들 수 있습니다. 현재 SVN 버전의 Django에서 사용할 수 있으며 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,)