In this Django REST Framework lesson we are going to learn about Django REST Framework Model Viewset, rather than writing your own viewsets, you’ll often want to use the existing base classes that provide a default set of behavior. for this we are using model viewset. the ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. the actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().
Open your views.py file and bring changes, this time we want to use model viewset.
1 2 3 4 5 6 7 8 9 10 11 12 |
from .models import Article from .serializers import ArticleSerializer from rest_framework import viewsets class ArticleViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing article instances. """ serializer_class = ArticleSerializer queryset = Article.objects.all() |
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 model viewsets.