In this Django REST Framework we are going to learn about Django REST Framework Generic Viewsets, this is another type of viewsets that we can use, basically The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default. In order to use a GenericViewSet class you’ll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
Now open your views.py and add this cod, this time we are going to use Generic Viewsets instead of Viewset.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from .models import Article from .serializers import ArticleSerializer from rest_framework import viewsets from rest_framework import mixins class ArticleViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin ): queryset = Article.objects.all() serializer_class = ArticleSerializer |
And this is our urls.py file.
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 of posting article, getting article, retrieving article, deleting article and updating article, but this time we have used generic viewsets.