django-filter:将ChoiceFilter与取决于请求的选项一起使用 [英] django-filter: Using ChoiceFilter with choices dependent on request
问题描述
我正在使用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
.
I am using django-filter and need to add a ChoiceFilter
with choices dependent on the request that I receive. I am reading the docs for ChoiceFilter but it says: This filter matches values in its choices argument. The choices must be explicitly passed when the filter is declared on the FilterSet
.
那么有什么方法可以在ChoiceFilter
中获得依赖于请求的选择?
So is there any way to get request-dependent choices in the ChoiceFilter
?
我实际上没有编写代码,但是下面是我想要的-
I haven't actually written the code but the following is what I want -
class F(FilterSet):
status = ChoiceFilter(choices=?) #choices depend on request
class Meta:
model = User
fields = ['status']
推荐答案
我一直都很努力,以至于发现了两种不同的实现方式! (均通过覆盖__init__
方法).受此问题启发的代码.
I've been looking too hard that I found two different ways of doing it! (both by overriding the __init__
method). Code inspired from this question.
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)]
})
这篇关于django-filter:将ChoiceFilter与取决于请求的选项一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!