问题:何时使用序列化器的create()和ModelViewset的create()perform_create()

我想澄清django-rest-framework有关创建模型对象的给定文档。到目前为止,我发现有3种方法来处理此类事件。

  1. 序列化器的create()方法。这是文档

    class CommentSerializer(serializers.Serializer):
    
        def create(self, validated_data):
            return Comment.objects.create(**validated_data)
    
  2. ModelViewsetcreate()方法。文献资料

    class AccountViewSet(viewsets.ModelViewSet):
    
        queryset = Account.objects.all()
        serializer_class = AccountSerializer
        permission_classes = [IsAccountAdminOrReadOnly]
    
  3. ModelViewsetperform_create()方法。文献资料

    class SnippetViewSet(viewsets.ModelViewSet):
    
        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)
    

这三种方法很重要,具体取决于您的应用程序环境。

但是什么时候我们需要使用每个create() / perform_create()函数?另一方面,我发现有人要求为单个发布请求调用modelviewsetcreate()和serializer的两个create方法create()

希望任何人都可以分享他们的一些知识来进行解释,这肯定会对我的开发过程有所帮助。

I want to clarify the given documentation of django-rest-framework regarding the creation of a model object. So far I found that there are 3 approaches on how to handle such events.

  1. The Serializer’s create() method. Here is the documentation

    class CommentSerializer(serializers.Serializer):
    
        def create(self, validated_data):
            return Comment.objects.create(**validated_data)
    
  2. The ModelViewset create() method. Documentation

    class AccountViewSet(viewsets.ModelViewSet):
    
        queryset = Account.objects.all()
        serializer_class = AccountSerializer
        permission_classes = [IsAccountAdminOrReadOnly]
    
  3. 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 account that two create methods were called for a single post request the modelviewset’s create() and serializer’s create().

Hopefully anyone would share some of their knowledge to explain and this will surely be very helpful in my development process.


回答 0

  1. 你会使用create(self, validated_data)节约型和“刺”的价值观为就像每个模型前场添加任何额外的细节到对象**validated_data一样。理想情况下,您只想在一个位置执行这种“探测”形式,因此create您的方法CommentSerializer是最佳的选择。最重要的是,您可能还想调用外部api,以在将帐户保存到自己的数据库之前在其旁边创建用户帐户。您应该将此create功能与结合使用ModelViewSet。永远想一想-“薄视图,厚串行器”。

例:

def create(self, validated_data):
    email = validated_data.get("email", None)
    validated.pop("email") 
    # Now you have a clean valid email string 
    # You might want to call an external API or modify another table
    # (eg. keep track of number of accounts registered.) or even
    # make changes to the email format.

    # Once you are done, create the instance with the validated data
    return models.YourModel.objects.create(email=email, **validated_data)
  1. 中的create(self, request, *args, **kwargs)函数在的父类中ModelViewSet定义。的主要功能如下:CreateModelMixinModelViewSetCreateModelMixin

    from rest_framework import status
    from rest_framework.response import Response
    
    
    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()
    

如您所见,以上create函数负责在序列化程序上调用验证并产生正确的响应。这样做的好处是,您现在可以隔离应用程序逻辑,而不必担心平凡和重复的验证调用以及处理响应输出:)。与create(self, validated_data)序列化器(您的特定应用程序逻辑所在的位置)中的结合使用时,这可以很好地工作。

  1. 现在您可能会问,为什么我们perform_create(self, serializer)只有一行代码才有一个单独的函数!好吧,这背后的主要原因是在调用save函数时允许自定义。您可能想要在调用之前提供额外的数据save (例如serializer.save(owner=self.request.user),如果我们没有perform_create(self, serializer),那么您将不得不重写,create(self, request, *args, **kwargs)而这违背了让mixin进行繁重而乏味的工作的目的。

希望这可以帮助!

  1. You would use create(self, validated_data) to add any extra details into the object before saving AND “prod” values into each model field just like **validated_data does. Ideally speaking, you want to do this form of “prodding” only in ONE location so the create method in your CommentSerializer is the best place. On top of this, you might want to also call external apis to create user accounts on their side just before saving your accounts into your own database. You should use this create function in conjunction withModelViewSet. Always think – “Thin views, Thick serializers”.

Example:

def create(self, validated_data):
    email = validated_data.get("email", None)
    validated.pop("email") 
    # Now you have a clean valid email string 
    # You might want to call an external API or modify another table
    # (eg. keep track of number of accounts registered.) or even
    # make changes to the email format.

    # Once you are done, create the instance with the validated data
    return models.YourModel.objects.create(email=email, **validated_data)
  1. The create(self, request, *args, **kwargs) function in the ModelViewSet is defined in the CreateModelMixin class which is the parent of ModelViewSet. CreateModelMixin‘s main functions are these:

    from rest_framework import status
    from rest_framework.response import Response
    
    
    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()
    

As you can see, the above create function takes care of calling validation on your serializer and producing the correct response. The beauty behind this, is that you can now isolate your application logic and NOT concern yourself about the mundane and repetitive validation calls and handling response output :). This works quite well in conjuction with the create(self, validated_data) found in the serializer (where your specific application logic might reside).

  1. Now you might ask, why do we have a separate perform_create(self, serializer) function with just one line of code!?!? Well, the main reason behind this is to allow customizeability when calling the save function. You might want to supply extra data before calling save (like serializer.save(owner=self.request.user) and if we didn’t have perform_create(self, serializer), you would have to override the create(self, request, *args, **kwargs) and that just defeats the purpose of having mixins doing the heavy and boring work.

Hope this helps!


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。