DRF custom view set
Viewset and APIView
Viewset | APIView |
---|---|
Uses DRF defined methods like ‘list’, ‘retrieve’, ‘create’, and so on | Users HTTP Verbs (GET, POST, and so on) |
Compatible with browsable API | Not compatible with the browsable API |
DRF Router compatible | Cannot use DRF Router |
Here are the official document for the Viewset and the APIView. In this post, we will take a look at how to implement a custom viewset.
Snippet of code for custom viewset
# polls/api_views.py
from rest_framework.response import Response
from rest_framework import viewsets
class CustomQuestionView(viewsets.ViewSet):
def list(self, request, format=None):
questions = [question.question_text for question
in Question.objects.all()]
return Response(questions)
After we finish up customizing the viewset class, we move to bridge the url.
# mysite/urls.py
from rest_framework import routers
from polls import api_views
router = routers.DefaultRouter()
router.register(r'custom_question',
api_views.CustomQuestionView, basename='poll')
When we check our work, we will get this screenshot.
Leave a comment