In this Django REST Framework we are going to learn about Django REST Framework Viewsets & Routers, a ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create(). the method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
There are different ways that you can implement viewsets, first way is that you can write your own viewsets, now we are going to change our views.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
from .models import Article from .serializers import ArticleSerializer from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 class ArticleViewSet(viewsets.ViewSet): def list(self, request): articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) def create(self, request): serializer = ArticleSerializer(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) def retrieve(self, request, pk=None): queryset = Article.objects.all() article = get_object_or_404(queryset, pk=pk) serializer = ArticleSerializer(article) return Response(serializer.data) def update(self, request, pk=None): article = Article.objects.all() serializer = ArticleSerializer(article, 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) def destroy(self, request, pk=None): article = Article.objects.all() article.delete() return Response(status=status.HTTP_204_NO_CONTENT) |
Because we’re using ViewSet classes rather than View classes, we actually don’t need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a Router class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
1 2 3 4 5 6 7 8 9 10 11 12 |
from django.urls import path, include from .views import ArticleViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('articles', ArticleViewSet, basename='articles') urlpatterns = [ path('', include(router.urls)) ] |
If you go to http://localhost:8000/articles/ you can see a browsable api from the django rest framework with same functionality, but this time we have used viewsets and routers.