2016-02-24 110 views
2

只有當某些條件匹配時,我纔想顯示Django管理員的某些列表過濾器。例如,我現在有3個過濾器:country,state,city。它們同時顯示的所有三個都會產生一個真正的混亂和一個非常長的邊欄,因爲它結合了一長串城市,州和國家。Django僅當條件匹配時才顯示列表過濾器

我想要做的是隻顯示國家第一,當一個國家被點擊時我想顯示該國的狀態和城市過濾器相同。這是默認可行的,或者我必須自己創建一個自定義過濾器?

list_filter = (
    ('loc_country_code', custom_titled_filter('country')), 
    ('loc_state', custom_titled_filter('state')), 
    ('loc_city', custom_titled_filter('city')), 
) 

回答

0

您可以創建自定義SimpleListFilter以在管理員上生成動態過濾器。在SimpleListFilter中,如果lookups方法返回一個空的元組/列表,則禁用過濾器(也從視圖中隱藏)。這可以用來控制何時出現某些過濾器。

這裏有一個基本的過濾器:

class CountryFilter(admin.SimpleListFilter): 

    title = 'Country' 
    parameter_name = 'country' 

    def lookups(self, request, model_admin): 
     """ Return a list of (country_id, country_name) tuples """ 
     countries = Country.objects.all() 
     return [(c.id, c.name) for c in countries] 

    def queryset(self, request, queryset): 
     ... 

下面是其中的選擇是基於以上的過濾器限制的過濾器:

class StateFilter(admin.SimpleListFilter): 

    title = 'State' 
    parameter_name = 'state' 

    def lookups(self, request, model_admin): 
     """ 
     Return a list of (state_id, state_name) tuples based on 
     country selected 
     """ 

     # retrieve the current country the user has selected 
     country_id = request.GET.get('country') 
     if country_id is None: 
      # state filter will be hidden 
      return [] 

     # only return states which belong in the country 
     states = State.objects.filter(country_id=country_id) 
     return [(s.id, s.name) for s in states] 

    def queryset(self, request, queryset): 
     ... 

的總體思路是使用你的過濾器類lookups限制後續過濾器上的選項。這些過濾器可以通過list_filter參數應用於管理員。

class MyAdmin(admin.ModelAdmin): 

    list_filter = [CountryFilter, StateFilter, CityFilter, ...] 
+0

究竟是我最終做了什麼。 –

相關問題