0

I'm reading the source code of mixin.py from rest_framework, here is the link to GitHub.

Let's take the CreateModelMixin class as an example, here is the code:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.settings import api_settings


class CreateModelMixin:
    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

I can understand the lines self.perform_create() and self.get_success_headers() because they are class methods defined within the class. But how did the line self.get_serializer(data=request.data) work?

My understandings so far:

  • The class CreateModelMixin did not inherit any classes
  • get_serializer() was not imported from other files
  • get_serializer() was not defined with class
Zheng
  • 93
  • 9
  • 2
    The expectation would be that the class which includes the mixin would implement the required method. On it's own the mixin cannot be used. In this case it needs to be *mixed in* with a class that implements the missing functionality. – flakes Apr 06 '23 at 03:50
  • For the nominal case, this mixin would be expected to be used along with a class which extends the [GenericAPIView](https://www.cdrf.co/3.1/rest_framework.generics/GenericAPIView.html) that provides this missing functionality. – flakes Apr 06 '23 at 03:54

0 Answers0