默认情况下,django admin的list_filter
提供模型选择中可用的所有过滤器。但除了那些我想要一个过滤器之外,我们可以说它是'无'过滤器。
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
过滤器
答案 0 :(得分: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,
}
<强>用法:强>
list_filter = (
('country_origin', AllValuesChoicesFieldListFilter),
)
答案 1 :(得分:0)
您不必制作自定义列表过滤器。只需使用django的AllValuesFieldListFilter
from django.contrib.admin.filters import AllValuesFieldListFilter
...
list_filter = [..., ('choice_field', AllValuesFieldListFilter)]
...