首页 文章

管理面板中的django choicefield过滤器

提问于
浏览
0

默认情况下,django admin的 list_filter 提供模型选择中可用的所有过滤器 . 但除了那些我想再多一个过滤器,让我们说'None'过滤器 .

class Mymodel:
    char choice field (choices=(('1', 'txt1', '2', 'txt2')), null=True)

class MymodelAdmin(admin.ModelAdmin):
    ...
    list_filter = [..., choice_field, ...]
    ...

这将在管理面板(右侧过滤器)中设置三个过滤器, All, 'txt1', 'txt2' . 对?如果没有从选项中分配值,我还需要一个过滤器'None' .

到目前为止我尝试了什么..

class ChoiceFieldFilter(admin.filters.ChoicesFieldListFilter):

    def __init__(self, *args, **kwargs):
        super(ChoiceFieldFilter, self).__init__(*args, **kwargs)

        self.lookup_val = [('', 'None')]

    def queryset(self, request, queryset):
        print self.lookup_val
        print  self.field.flatchoices
        if self.lookup_val == '':
            return queryset.filter(choice_field='')
        else:
            return queryset.filter(choice_field=self.lookup_val)

    def choices(self, cl):
        pass

然后在管理类中

list_filter = [..., ('choice_field', ChoiceFieldFilter), ...]

但它无法正常工作,我无法在django admin中看到 None 过滤器

2 回答

  • 1

    默认情况下,admin.AllValuesFieldListFilter返回一个选项的值,而不是选择的详细名称 . 因此,为了解决它,使用修改后的admin.AllValuesFieldListFilter .

    class AllValuesChoicesFieldListFilter(admin.AllValuesFieldListFilter):
    
        def choices(self, changelist):
            yield {
                'selected': self.lookup_val is None and self.lookup_val_isnull is None,
                'query_string': changelist.get_query_string({}, [self.lookup_kwarg, self.lookup_kwarg_isnull]),
                'display': _('All'),
            }
            include_none = False
    
            # all choices for this field
            choices = dict(self.field.choices)
    
            for val in self.lookup_choices:
                if val is None:
                    include_none = True
                    continue
                val = smart_text(val)
                yield {
                    'selected': self.lookup_val == val,
                    'query_string': changelist.get_query_string({
                        self.lookup_kwarg: val,
                    }, [self.lookup_kwarg_isnull]),
    
                    # instead code, display title
                    'display': choices[val],
                }
            if include_none:
                yield {
                    'selected': bool(self.lookup_val_isnull),
                    'query_string': changelist.get_query_string({
                        self.lookup_kwarg_isnull: 'True',
                    }, [self.lookup_kwarg]),
                    'display': self.empty_value_display,
                }
    

    Usage:

    list_filter = (
            ('country_origin', AllValuesChoicesFieldListFilter),
        )
    
  • 0

    您不必进行自定义列表过滤 . 只需使用django的AllValuesFieldListFilter

    from django.contrib.admin.filters import AllValuesFieldListFilter
    ...
    list_filter = [..., ('choice_field', AllValuesFieldListFilter)]
    ...
    

相关问题