Gar*_*ain 5 python django filter choicefield django-filter
我正在使用 django-filter ,需要ChoiceFilter根据我收到的请求添加一个选项。我正在阅读 ChoiceFilter 的文档,但它说:This filter matches values in its choices argument. The choices must be explicitly passed when the filter is declared on the FilterSet。
那么有什么方法可以在 中获得依赖于请求的选择吗ChoiceFilter?
我实际上还没有编写代码,但以下是我想要的 -
class F(FilterSet):
status = ChoiceFilter(choices=?) #choices depend on request
class Meta:
model = User
fields = ['status']
Run Code Online (Sandbox Code Playgroud)
我一直在努力寻找,发现了两种不同的方法!(两者都通过重写__init__方法)。代码灵感来自这个问题。
class LayoutFilterView(filters.FilterSet):
supplier = filters.ChoiceFilter(
label=_('Supplier'), empty_label=_("All Suppliers"),)
def __init__(self, *args, **kwargs):
super(LayoutFilterView, self).__init__(*args, **kwargs)
# First Method
self.filters['supplier'].extra['choices'] = [
(supplier.id, supplier.id) for supplier in ourSuppliers(request=self.request)
]
# Second Method
self.filters['supplier'].extra.update({
'choices': [(supplier.id, supplier.name) for supplier in ourSuppliers(request=self.request)]
})
Run Code Online (Sandbox Code Playgroud)
该函数ourSuppliers只是返回一个 QuerySet 用作选择
def ourSuppliers(request=None):
if request is None:
return Supplier.objects.none()
company = request.user.profile.company
return Supplier.objects.filter(company=company)
Run Code Online (Sandbox Code Playgroud)