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 documentation
class CommentSerializer(serializers.Serializer):
def create(self, validated_data):
return Comment.objects.create(**validated_data)
The ModelViewset create()
method. Documentation
class AccountViewSet(viewsets.ModelViewSet):
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
The ModelViewset perform_create()
method. Documentation
class 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()
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…