【问题标题】:Django show list filter only if condition matchesDjango 仅在条件匹配时显示列表过滤器
【发布时间】:2023-03-22 16:25:01
【问题描述】:

我只想在某个条件匹配时为 Django 管理员显示某些列表过滤器。例如,我现在有 3 个过滤器:countrystatecity。同时显示所有 3 个会产生真正的混乱和很长的侧边栏,因为它结合了一长串城市、州和国家/地区。

我想做的是首先只显示国家,当点击一个国家时,我想显示该国家的州,城市过滤器也是如此。这是默认情况下可行还是我必须自己创建自定义过滤器?

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

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    您可以创建自定义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, ...]
    

    【讨论】:

    • 我最终做了什么。
    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多