Home > Enterprise >  use of mixins class defined in Django rest framework
use of mixins class defined in Django rest framework

Time:02-15

What is the actual use of Mixins class? I don't really get it. All the mixins classes like CreateModelmixin, Listmixin, etc features are already available in class-based view like ListCreateApiView.

For eg:

class ExampleView(ListCreateAPIView
                 DestroyAPIView,
               RetrieveUpdateAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer
    pagination_class = CustomPageNumberPagination

Using mixins we can do it by following:

class ExampleView(ListAPIView,
                     mixins.CreateModelMixin):
        queryset = Example.objects.all()
        serializer_class = ExampleSerializer
        pagination_class = CustomPageNumberPagination

When I check https://www.cdrf.co/ I see the methods that are available in CreateModelMixing are the following:

def create(self, request, *args, **kwargs): 
def get_success_headers(self, data): 
def perform_create(self, serializer):

These methods are already available in ListCreateApiView, then why Django went to create this useless class??

CodePudding user response:

The ListCeateAPIView class uses the CreateModelMixin mixin. Indeed, take a look at the Ancestors (Method Resolution Order; MRO) of the ListCreateAPIView [classy-drf]. It contains the CreateModelMixin.

Most APIViews that Django made are just an APIView and a bunch of mixins. These mixins define the actual behavior. The ListCreateAPIView (and other subclasses of the APIView) are just packs of mixins and the APIView.

This is also the use-case of a mixin: mixing in certain logic in a class. There are multiple APIViews that allow creating an object like a CreateAPIView, ListCreateAPIView and the ModelViewSet. Instead of implementing the same logic in all these classes, or work with inheritance of a base-class that would only be linear, one can mix it in all hierarchies by making use of a mixin that implements the logic.

It is also useful to work with these mixins if you for example want to construct a subclass of an APIView yourself that does something sophisticated, and at the same time mix in logic for the create handle that does not do such sophisticated things.

If you use a mixin however, that is usually written before the base class, so:

#              mixin first            
  • Related