Loran
Loran

Reputation: 842

Filter is not working in Django Rest Framework

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

What I want is=>

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

Upvotes: 0

Views: 1716

Answers (1)

JPG
JPG

Reputation: 88429

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

Upvotes: 1

Related Questions