使用MethodFilter使用django-filters在get请求中使用多个值进行过滤

时间:2015-11-19 10:27:30

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

我尝试使用MethodFilter设置过滤器来创建一个FilterSet,期望多个值如下:

Filters.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,只有在方法filter_first_filter的值中传递了thing2而不是[' thing1',&# 39; thing2]。

如何更改此行为?

1 个答案:

答案 0 :(得分:0)

我只知道为什么那不起作用。

使用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())