在成功实现了crispy-forms
和django-tables 2
后,我来使用django-filter
在表格中实现过滤,我正在撕掉我的头发。
首先,我发现它记录得更糟,可能这就是为什么我找不到我需要的信息。
我希望有一个下拉形式,我可以选择天气来显示All users
,Superusers
,Normal users
。
所以我已经从BooleanFilter
转移到了ChoiceFilter
并有自定义选择。
class UserFilter(filters.FilterSet):
SUPERUSER_CHOICES = {
('', 'All'),
('True', 'Superusers'),
('False', 'Normal users')
}
username = filters.CharFilter(field_name='username', lookup_expr='icontains')
is_superuser = filters.ChoiceFilter(field_name='is_superuser', lookup_expr='exact',
choices=SUPERUSER_CHOICES,)
test = filters.Filter
class Meta:
model = User
fields = ['username', 'is_superuser']
这就是我得到的:
为什么这些破灭?如何摆脱它们?
也许我甚至不需要使用ChoiceFilter
来改变选项的价值?
你需要在每个empty_label
的None
上将ChoiceFilter
设置为the docs here:
is_superuser = filters.ChoiceFilter(
field_name='is_superuser',
lookup_expr='exact',
choices=SUPERUSER_CHOICES,
empty_label=None
)
另见this answer以更好地理解Django的empty_label
。