我正在使用django-filter,需要添加一个This filter matches values in its choices argument. The choices must be explicitly passed when the filter is declared on the FilterSet
,其选择取决于我收到的请求。我正在阅读ChoiceFilter的文档,但上面写着:ChoiceFilter
。
那么有什么方法可以在class F(FilterSet):
status = ChoiceFilter(choices=?) #choices depend on request
class Meta:
model = User
fields = ['status']
中获得依赖于请求的选择?
我实际上没有编写代码,但是下面是我想要的-
{{1}}
答案 0 :(得分:0)
我一直都很努力,以至于我发现了两种不同的方法! (均通过覆盖__init__
方法)。代码受this问题的启发。
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)]
})