Django Rest Framework ViewSet中的filter_fields被忽略

时间:2019-01-17 19:52:37

标签: django django-rest-framework

我正在尝试对视图进行一些基本的相等过滤,如果我了解documentation,则只需要定义filter_fields()字段即可。

好吧,它们似乎被忽略了(/api/organizations?ticker=AMZN列出了所有内容,而不是过滤到单个记录):

class OrganizationViewSet(viewsets.ModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrganizationSerializer
    pagination_class = CustomPagination
    filter_fields = ('sector', 'industry', 'marketplace')

    @staticmethod
    def pack_persons_to_url(request, data):
        data["persons"] = request.build_absolute_uri("/api/persons/%s/" % data["symbol"])

    def list(self, request, *args, **kwargs):
        response = super(OrganizationViewSet, self).list(request, *args, **kwargs)
        for element in response.data["results"]:
            self.pack_persons_to_url(request, element)
        return response

    def retrieve(self, request, *args, **kwargs):
        response = super(OrganizationViewSet, self).retrieve(request, *args, **kwargs)
        self.pack_persons_to_url(request, response.data)
        return response

前三个字段是FK,tickerCharField。我需要修复什么才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

您需要将DjangoFilterBackend添加到视图集的过滤器后端

filter_backends = (backends.DjangoFilterBackend, )