python - django-filter:使用 ChoiceFilter 并根据请求进行选择

标签 python django filter django-filter choicefield

我正在使用 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只是返回一个查询集用作选择

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

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

关于python - django-filter:使用 ChoiceFilter 并根据请求进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53866157/

相关文章:

python - 以二维特征数组作为输入的高斯过程 - scikit-learn

python - 限制 Python 的语法以安全地执行用户代码。这是一种安全的方法吗?

python - 通过 REST API 使用 Django 与 salesforce 对话

django - Gunicorn 动态反射(reflect)更改的代码

python - 如何在 Django 中使用并发进程记录到单个文件而不使用独占锁

python - 过滤掉超过一定数量 NaN 的行

python - 是换行符 "\n"2个字符还是1个字符

python - Django 不像 python 那样使用 pyodbc

R,使用 dplyr::filter() 和 %in% 将列名作为参数传递给函数

java - hbase 仅获取行而不是空列(使用条件的现有列)- 使用 java 在 hbase 表中