django-rest-framework Mixins [Intermediate] Creating Custom Mixins


Example


DRF offers the chance to further customize the behavior of the generic views/viewsets by allowing the creation of custom mixins.

How to:

To define a custom mixin we just need to create a class inheriting from object.

Let's assume that we want to define two separate views for a model named MyModel. Those views will share the same queryset and the same serializer_class. We will save ourselves some code repetition and we will put the above in a single mixin to be inherited by our views:

  • my_app/views.py (that is not the only file option available to place our custom mixins, but it is the less complex):

    from rest_framework.generics import CreateAPIView, RetrieveUpdateAPIView
    from rest_framework.permissions import IsAdminUser
    
    class MyCustomMixin(object):
        queryset = MyModel.objects.all()
        serializer_class = MyModelSerializer
    
    class MyModelCreateView(MyCustomMixin, CreateAPIView):
        """
        Only an Admin can create a new MyModel object
        """
        permission_classes = (IsAdminUser,)
        
        Do view staff if needed...
    
    class MyModelCreateView(MyCustomMixin, RetrieveUpdateAPIView):
        """
        Any user can Retrieve and Update a MyModel object
        """
        Do view staff here...
    

Conclusion:

Mixins are essentially blocks of reusable code for our application.