abolotnov
abolotnov

Reputation: 4332

filter_fields in django rest framework viewset are ignored

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?

Upvotes: 6

Views: 5402

Answers (2)

ipetrik
ipetrik

Reputation: 2054

I was experiencing this after upgrading to django-filters 22.1. It seems filter_fields was renamed to filterset_fields.

Upvotes: 13

ivissani
ivissani

Reputation: 2664

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

filter_backends = (backends.DjangoFilterBackend, )

Upvotes: 5

Related Questions