filter_fields in django rest framework viewset are ignored

Viewed 3491

I am trying to get some basic equality filtering for my view and if I understand the documentation, I only need the filter_fields() field defined.

Well, they seem to be ignored (/api/organizations?ticker=AMZN lists everything instead of filtering down to a single record):

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

The first three fields are FKs and the ticker is a CharField. What do I need to fix to make it all work right?

1 Answers

You need to add DjangoFilterBackend to the filter backends of your viewset

filter_backends = (backends.DjangoFilterBackend, )
Related