2012-08-24 2 views
26

django admin에 대한 일반 필터 인 'is_staff'및 'is_superuser'대신 사용자 정의 필터를 만들고 싶습니다. 나는이 list_filter을 장고 문서에서 읽었다. 이 같은 list_display에 대한 사용자 정의 기능을장고 관리의 list_filter에 대한 사용자 정의 필터 만들기

from datetime import date 

from django.utils.translation import ugettext_lazy as _ 
from django.contrib.admin import SimpleListFilter 

class DecadeBornListFilter(SimpleListFilter): 
    # Human-readable title which will be displayed in the 
    # right admin sidebar just above the filter options. 
    title = _('decade born') 

    # Parameter for the filter that will be used in the URL query. 
    parameter_name = 'decade' 

    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 (
      ('80s', _('in the eighties')), 
      ('90s', _('in the nineties')), 
     ) 

    def queryset(self, request, queryset): 
     """ 
     Returns the filtered queryset based on the value 
     provided in the query string and retrievable via 
     `self.value()`. 
     """ 
     # Compare the requested value (either '80s' or '90s') 
     # to decide how to filter the queryset. 
     if self.value() == '80s': 
      return queryset.filter(birthday__gte=date(1980, 1, 1), 
            birthday__lte=date(1989, 12, 31)) 
     if self.value() == '90s': 
      return queryset.filter(birthday__gte=date(1990, 1, 1), 
            birthday__lte=date(1999, 12, 31)) 

class PersonAdmin(ModelAdmin): 
    list_filter = (DecadeBornListFilter,) 

하지만 난 이미 만든 : 사용자 정의 필터를이 방식으로 작동

def Student_Country(self, obj): 
    return '%s' % obj.country 
Student_Country.short_description = 'Student-Country' 

이 가능 내가 쓰는 대신 list_filter에 list_display에 대한 사용자 정의 기능을 사용할 수 있나요 list_filter에 대한 새로운 사용자 정의 함수? 모든 제안이나 개선을 환영합니다 .. 이것에 대한 지침이 필요합니다 ... 감사합니다 ...

+0

에 http : // 유래. com/questions/12215751/can-i-make-list-filter-in-django-admin-to-only-show-referenced-foreignkeys – user956424

답변

1

list_display 귀하의 list_display 메서드는 문자열을 반환하지만, 내가 올바르게 이해한다면, 선택을 허용하는 필터를 추가하는 것입니다 학생 국가 중, 맞습니까?

이 단순 관계 필터와 실제로 "학생 - 국가"목록 표시 열에 대해서도 사용자 지정 필터 클래스 또는 사용자 지정 목록 표시 방법을 만들 필요가 없습니다. 이 충분 :

class MyAdmin(admin.ModelAdmin): 
    list_display = ('country',) 
    list_filter = ('country',) 

in the docs 설명으로 장고, list_filter을 수행하는 방법은, 당신이 필터 클래스를 내장 사전에 제공 자동으로 일치하는 필드로 처음이다; 이러한 필터에는 CharField 및 ForeignKey가 포함됩니다.

list_display 마찬가지로 관련 개체를 검색 및 이들의 유니 값 (위에서 제공된 방법에서와 동일)를 반환하여 통과 필드를 사용하여 변경 목록 컬럼의 인구를 자동화한다.

5

SimpleListFilter를 확장하여 관리 필터에 맞춤 필터를 실제로 추가 할 수 있습니다. 당신이 위에서 사용 된 국가 관리 필터에 '아프리카의 대륙 필터를 추가하려는 경우 예를 들어, 다음과 같은 작업을 수행 할 수 있습니다

admin.py에서 :

from django.contrib.admin import SimpleListFilter 

class CountryFilter(SimpleListFilter): 
    title = 'country' # or use _('country') for translated title 
    parameter_name = 'country' 

    def lookups(self, request, model_admin): 
     countries = set([c.country for c in model_admin.model.objects.all()]) 
     return [(c.id, c.name) for c in countries] + [ 
      ('AFRICA', 'AFRICA - ALL')] 

    def queryset(self, request, queryset): 
     if self.value() == 'AFRICA': 
      return queryset.filter(country__continent='Africa') 
     if self.value(): 
      return queryset.filter(country__id__exact=self.value()) 

class CityAdmin(ModelAdmin): 
    list_filter = (CountryFilter,) 
관련 문제