django-filter: Using ChoiceFilter with choices dependent on request

坚强是说给别人听的谎言 提交于 2019-12-11 04:26:18

问题


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.

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']

回答1:


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)]
        })


来源:https://stackoverflow.com/questions/53866157/django-filter-using-choicefilter-with-choices-dependent-on-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!