【问题标题】:Filter with multiple values in get request with django-filters using a MethodFilter使用 MethodFilter 使用 django-filters 在获取请求中过滤多个值
【发布时间】:2016-02-21 10:31:36
【问题描述】:

我正在尝试创建一个 FilterSet,其过滤器设置为 MethodFilter 期望多个值:

过滤器.py

class MyFilter(django_filters.FilterSet):
    first_filter = django_filters.MethodFilter()

    class Meta:
        model = myModel
        fields = ['first_filter']

    def filter_first_filter(self, queryset, value):
        # I expect value to setup with an array of values
        myquery = Q()
        return queryset.filter(myquery)

Views.py

class MyView(RetrieveAPIView):

    def get(self, request, format=None, **kwargs):
        filter = MyFilter(request.query_params, queryset=myModel.objects.all())
        # Other things go there using the filter instanciated

所以当我用这种 URL /my_view?first_filter=thing1&first_filter=thing2 请求视图时,只有 thing2 被传入方法 filter_first_filter 的值,而不是 ['thing1', 'thing2]。

如何改变这种行为?

【问题讨论】:

标签: django django-rest-framework django-filter


【解决方案1】:

我只是想通了为什么这不起作用。

使用 request.query_params 实例化 FilterSet 的事实是错误的,因为 query_params 是 QueryDict 并且 QueryDict 的 get 函数仅返回最后一个元素。所以要解决这个问题,我应该这样做:

class MyView(RetrieveAPIView):

    def get(self, request, format=None, **kwargs):
        dict_params = dict(request.query_params.iterlists())
        filter = MyFilter(dict_params, queryset=myModel.objects.all())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 2018-12-04
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多