Reputation: 5723
I have the below views.py file for my class based view.
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .permissions import IsOwner, IsNotBlacklistedUser
from rest_framework import filters
from django_filters import rest_framework as filters_django
from core.models import Book
from .serializers import BookSerializer, AllBookSerializer
class BookApiView(APIView):
authentication_classes = (JSONWebTokenAuthentication, )
permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
filter_backends = (filters_django.DjangoFilterBackend,)
filterset_fields = ('title',)
def get(self, request):
books = Book.objects.filter(
user=request.user.id, is_published=True).order_by('-title')
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
def post(get, request):
data = request.data
serializer = BookSerializer(data=data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
I am unable to see any filter option when i load this view in the django rest framework UI . I am not sure how i should be doing this. Can someone point out what i might have to do extra to get this working . I have also added 'django_filters'
to my settings.py file.
Thanks in advance.
Upvotes: 0
Views: 201
Reputation: 755
You can either use ViewSets.
class BookApiViewSet(CreateModelMixin, ListModelMixin, GenericViewSet):
authentication_classes = (JSONWebTokenAuthentication, )
permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
filter_backends = (filters_django.DjangoFilterBackend,)
filter_fields = ('title',)
or generic APIViews
class BookListCreateAPIView(generics.ListCreateAPIView):
authentication_classes = (JSONWebTokenAuthentication, )
permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
filter_backends = (filters_django.DjangoFilterBackend,)
filter_fields = ('title',)
or you can extend GenericAPIView and write filters manually.
class BookApiView(GenericAPIView):
authentication_classes = (JSONWebTokenAuthentication, )
permission_classes = (IsAuthenticated, IsNotBlacklistedUser)
filter_backends = (filters_django.DjangoFilterBackend,)
filter_fields = ('title',)
queryset = self.filter_queryset(self.get_queryset())
def get(self, request, *args, **kwargs):
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
Note: I didn't test codes you may need to tweak little.
Upvotes: 2