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 filesget_serializer()
was not defined with class