Search code examples
djangofilterdjango-rest-frameworkdjango-filter

Filter is not working in Django Rest Framework


I would like to filter my data like assumes I have one model =>

  • User
    • UserID
    • UserName
    • UserDescription

What I want is=>

  • If i select like => api/user/?userid=1 , It should return only userid == 1 result.
  • If I select like => api/user/?username=test, It should return only username == test result.

What I have done?

I installed django-filter and add this

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

to setting.py and I test like that but

why I get all of my records? even URL is select only userid = 1 api/user/?userid=1

and

If I test with the wrong URL parameter and I got all records even the wrong parameter.

I do the exact same way with this => https://www.django-rest-framework.org/api-guide/filtering/#generic-filtering

Update

Here is View

class LeaveViewSet(viewsets.ModelViewSet):
    queryset = Leave.objects.all()
    serializer_class = LeaveSerializer

Solution

  • You should specify the filterset_fields - (doc) attribute

    class LeaveViewSet(viewsets.ModelViewSet):
        queryset = Leave.objects.all()
        serializer_class = LeaveSerializer
        filterset_fields = ['user','other_fields']

    Since you want to lookup a nested relation, you might specify the nested lookup as

    filterset_fields = ['user__id','user__username']
    

    and hence the URL will become, api/user/?user__id=1