django-rest-framework Mixins [Introductory] List of Mixins And Usage on Views/Viewsets


Example


List of available mixins:

  • ListModelMixin: provides a .list() method to the view/viewset
  • RetrieveModelMixin: provides a .retrieve() method to the view/viewset
  • CreateModelMixin: provides a .create() method to the view/viewset
  • UpdateModelMixin: provides a .update() method to the view/viewset
  • DestroyModelMixin: provides a .destroy() method to the view/viewset

We can mix and match the mixins in our generic views and viewsets, in order to give them the corresponding utility that we need:

  1. An API view with .list() .create() and .destroy() methods?
    Inherit from the GenericAPIView and combine the appropriate mixins:

    from rest_framework import mixins, generics
    
    from myapp.models import MyModel
    from myapp.serializers import MyModelSerializer
    
    class MyCustomAPIView(mixins.ListModelMixin, 
                          mixins.CreateModelMixin,
                          mixins.DestroyModelMixin,
                          generics.GenericAPIView):
    
        queryset = MyModel.objects.all()
        serializer_class = MyModelSerializer
    
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            return self.create(request, *args, **kwargs)
    
        def delete(self, request, *args, **kwargs):
            return self.destroy(request, *args, **kwargs)
    
  2. A viewset with only a .list() and .update() methods?
    Inherit from the GenericViewSet and add the appropriate mixins:

    from rest_framework import mixins
    
    class MyCustomViewSet(mixins.ListModelMixin,
                          mixins.UpdateModelMixin,
                          viewsets.GenericViewSet):
        pass
    

    Yes, it was that easy!!


To conclude, we can mix and match every mixin we need and utilize it to customize our views and their methods in any possible combination!