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.

那么有没有办法在 ChoiceFilter 中获得依赖于请求的选择?

我没有真正写过代码,但下面是我想要的-

class F(FilterSet):
    status = ChoiceFilter(choices=?) #choices depend on request
    class Meta:
        model = User
        fields = ['status']

我一直在努力寻找,以至于我找到了两种不同的方法! (两者都通过覆盖 __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)]
        })

函数ourSuppliers只是为了return一个QuerySet作为choices

def ourSuppliers(request=None):
    if request is None:
        return Supplier.objects.none()

    company = request.user.profile.company
    return Supplier.objects.filter(company=company)