Search code examples
django-rest-frameworkdjango-filters

django-filter not working with django-rest-framework


I'm using Django 2.0, Django REST Framework and Django Filters to filter the queryset.

I have installed django-filters and added to INSTALLED_APPS as django_filters.

The settings file has

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication'
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

and the view class is like

class AmountGivenViewSet(viewsets.ModelViewSet):
    serializer_class = AmountGivenSerializer
    permission_classes = (IsAuthenticated,)
    filterset_fields = ('contact__id',)

    def get_queryset(self):
        queryset = AmountGiven.objects.filter(
            contact__user=self.request.user
        )
        query = self.request.query_params.get('q', None)

        if query:
            queryset = queryset.filter(
                Q(transaction_number=query) |
                Q(comment__contains=query) |
                Q(amountreturned__transaction_number=query) |
                Q(amountreturned__comment__contains=query)
            )

        return queryset

AmountGiven model has a foreign key to contact and thus want to filter based on contact_id.

Now when I try the following URL

https://example.com/api/amount-given/?contact__id=3634de36-181c-4414-93fc-f08e3d70f1e3

It does not filter the result and returns all AmountGiven records.


Solution

  • Try changing filterset_fields for "filter_fields" like this:

    class AmountGivenViewSet(viewsets.ModelViewSet):
        serializer_class = AmountGivenSerializer
        permission_classes = (IsAuthenticated,)
        filterset_fields = ('contact__id',)