In this Django REST Framework lesson we are going to learn about Django REST Framework Mixins, one of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns. the generic views provided by REST framework allow you to quickly build API views that map closely to your database models. if the generic views don’t suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
OK now we are changing our views.py file, and we are removing the previous codes, by using this code you can add, get, update and delete the data. also there are separate mixins for different functionalities, for example posting article we are going to use CreateModelMixin, for getting the articles we are using ListModelMixin, for updating we are using UpdateModelMixin and for deleting we can use DestroyModelMixin.
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 |
from .models import Article from .serializers import ArticleSerializer from rest_framework import generics from rest_framework import mixins class ArticleList(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, ): serializer_class = ArticleSerializer queryset = Article.objects.all() def get(self, request): return self.list(request) def post(self, request): return self.create(request) class ArticleDetails(generics.GenericAPIView, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin): serializer_class = ArticleSerializer queryset = Article.objects.all() lookup_field = 'id' def get(self, request, id): return self.retrieve(request, id=id) def put(self, request, id=None): return self.update(request, id) def delete(self, request, id): return self.destroy(request, id) |
This is our urls.py file.
1 2 3 4 5 6 7 8 |
from django.urls import path from .views import ArticleList, ArticleDetails urlpatterns = [ path('articles/', ArticleList.as_view()), path('articles/<int:id>/', ArticleDetails.as_view()) ] |
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 view and mixins.