Instagram
youtube
Facebook
Twitter

Generic API Views and Mixins in Django REST Framework

In this tutorial, we will explore the concepts of Generic API Views and Mixins in Django REST Framework (DRF). We'll use the Students model and StudentsSerializer from our previous tutorials to demonstrate how to create a comprehensive API using these powerful tools.

Generic API Views

Generic API Views in DRF are pre-built views that provide a simple and consistent way to perform common operations on resources. They abstract away a lot of coding that developers would otherwise need to write for handling basic CRUD actions.

DRF provides various generic views, such as:

  • ListAPIView: Handles listing multiple instances of a resource.

  • CreateAPIView: Handles creating new instances of a resource.

  • RetrieveAPIView: Handles retrieving a single instance of a resource.

  • UpdateAPIView: Handles updating an instance of a resource.

  • DestroyAPIView: Handles deleting an instance of a resource.

Let's use Generic API View to handle listing all students and creating new student records:

Code/views.py

from rest_framework.generics import ListAPIView, CreateAPIView
from .models import Students
from .serializers import StudentsSerializer

class StudentsListCreateView(ListAPIView, CreateAPIView):
    queryset = Students.objects.all()
    serializer_class = StudentsSerializer

Result

Mixins

Mixins are small, reusable components that encapsulate specific behaviors that can be added to views. They allow developers to create custom views by combining different mixins, providing the flexibility to build views with the required functionality without duplicating code.

DRF offers various mixins, such as:

  • CreateModelMixin: Handles creating a new instance of a resource.

  • RetrieveModelMixin: Handles retrieving a single instance of a resource.

  • UpdateModelMixin: Handles updating an instance of a resource.

  • DestroyModelMixin: Handles deleting an instance of a resource.

  • ListModelMixin: Handles listing multiple instances of a resource.

Here's an example of how mixins are used to build a custom view:

Code/views.py

from rest_framework import mixins
from rest_framework import generics
from .models import Students
from .serializers import StudentsSerializer

class StudentsDetailView(mixins.RetrieveModelMixin,
                         mixins.UpdateModelMixin,
                         mixins.DestroyModelMixin,
                         generics.GenericAPIView):
    queryset = Students.objects.all()
    serializer_class = StudentsSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

Result