'Django filters with APIVIew return the complete queryset
I'm trying to use django filter with APIVIew like I saw in this post and I'm geting an unexpected behavior:
If the word passed on filter doesn't exists, it return nothing - OK
If the word passed on filter exists, it return the complete queryset.
I tried to use filters with ModelViewSet before and it works, but I have no success with APIView. I'm using the following code:
views:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from core.models import Profile
from core.serializers import ProfileSerializer
from django_filters.rest_framework import DjangoFilterBackend
class ProfileFilter(DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
filter_class = self.get_filter_class(view, queryset)
if filter_class:
return filter_class(request.query_params, queryset=queryset, request=request).qs
return queryset
class ListProfileView(APIView):
serializer_class = ProfileSerializer
filter_fields = ('nome', 'link')
queryset = Profile.objects.all()
def get(self, request, format=None):
queryset = Profile.objects.all()
ff = ProfileFilter()
filtered_queryset = ff.filter_queryset(request, queryset, self)
if filtered_queryset.exists():
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response([], status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
model:
from django.db import models
class Profile(models.Model):
nome = models.CharField(max_length=200, null=False, blank=False)
link = models.CharField(max_length=200, null=False, blank=False)
serializers:
from rest_framework.serializers import ModelSerializer
from core.models import Profile
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
