I want to clarify the given documentation of Django-rest-framework regarding the creation of a model object. So far I have found that there are 3 approaches on how to handle such events.
The Serializer's
create()
method. Here is the documentationclass CommentSerializer(serializers.Serializer): def create(self, validated_data): return Comment.objects.create(**validated_data)
The ModelViewset
create()
method. Documentationclass AccountViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly]
The ModelViewset
perform_create()
method. Documentationclass SnippetViewSet(viewsets.ModelViewSet): def perform_create(self, serializer): serializer.save(owner=self.request.user)
These three approaches are important depending on your application environment.
But when do we need to use each create() / perform_create()
function? On the other hand, I found some accounts that two create methods were called for a single post request the ModelViewSet
's create()
and serializer's create()
.