2

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.

1
  • Does any other filter has same problem? Commented Aug 31, 2018 at 20:31

1 Answer 1

6

Try changing filterset_fields for "filter_fields" like this:

class AmountGivenViewSet(viewsets.ModelViewSet):
    serializer_class = AmountGivenSerializer
    permission_classes = (IsAuthenticated,)
    filterset_fields = ('contact__id',)
Sign up to request clarification or add additional context in comments.

2 Comments

The official django-filter doc suggest us to use filterset_fields
Just a heads up - the filter_fields parameter has been deprecated and renamed to filterset_fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.