[Django]-When and how to validate data with Django REST Framework

10👍

Here’s the implementation of the create method that you overrided, taken from the mixins.CreateModelMixin class:

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)

As you can see, it gets the serializer, validates the data and performs the creation of the object from the serializer validated data.

If you need to manually control the creation of the object, perform_create is the hook that you need to override, not create.

def perform_create(self, serializer):
    # At this, the data is validated, you can do what you want
    # by accessing serializer.validated_data
👤Seb D.

Leave a comment