The difference between create in Django rest_framework Serializer and create/perform_create in Views

The difference between create in Django rest_framework Serializer and create/perform_create in Views


For the back-end, the separation of front-end and back-end can make both front-end and front-end development more comfortable. Like all pleasures, every pleasure comes with a price. The cost of separating the front-end and back-end is that the back-end has to face a huge number of modular functional components and the conventional usage and rewriting of these components. I have some experience, and I hope to discuss with you the differences between create() in Serializer and create()/perform_create() in Views .


1 Serializer serializer

1.1 Serializer function

The serializer is a component of rest_framework and has two functions:

  • Serialization : Convert objects in python into json/xml format strings . The object here refers to the database object, because rest_framework uses ORM to operate the database. Its function is intuitively to pass the data in the database to the front end through the interface. Because of the use of ORM, the data from the database to the interfaceConvertThe process is described as serialization . In fact, a more accurate description should be [transmittable] or [converted into a data type that can be directly used by the front end], which is easier to understand.
  • Deserialization : Convert json/xml format string into an object in python . Functionally speaking,Deserialization is the reverse process of serialization. But similarly, the method of literal translation from English to Chinese will always bring various obstacles to understanding. A more accurate description should be [string objectification] or [storable].

Compared with the non-separation of front and back ends, Serializer takes on part of the views

2.2 create in Serializer

The process of serialization() is generally a read operation, and in most cases it should not involve the use of create(). Therefore, when Serializer overrides create(), it can only deserialize ( string ----> database ), that is, save the interface data to the database.

  • create() method in Serializers

    
    from rest_framework import serializers
    
    class MyModelSerializer(serializers.ModelSerializer):
    	"""
    	一个序列化器
    	"""
        class Meta:
            model = MyModel
            fields = '__all__'
    
    	# Serializers中的create()方法
        def create(self, validated_data):
            ## your code
            return super().create(validated_data)
    

    The small piece of code above is a typical serializer. Here we rewrite the Serializer's create(). You can see that the create() method here has avalidated_dataParameters, what does this mean? I think you are smart and have guessed the answer: that is, this data is passed from the front end and has been verified . Who has verified it? Yes, it is Serializer. Many people may still remember that Serializer provides many fields, similar to the fields in models. At that time, I was still thinking about what I said this thing was used for. Looking back now, I think many people, like me, have suddenly become enlightened. Remember, never forget the functionality of Serializer . for example:

    from rest_framework import serializers
    
    class MyModelSerializer(serializers.ModelSerializer):
    	"""
    	一个序列化器
    	"""
        class Meta:
            model = MyModel
            fields = '__all__'
    
    	# Serializers中的create()方法
        def create(self, validated_data):
            ## your code
            return super().create(validated_data)
        
        # 定义的一个字段
        my_bool = BooleanField()
    

    Above I defined a field: my_bool. Acceptable values ​​for this field are a boolean (0/1). If you pass other values, an error will be reported. Then, it is obvious that the effect of overriding the create() method in Serializer has been revealed:Perform secondary processing on the verified front-end input parameters of Serializer. By default, after the serializer processing is completed, a sample instance will be returned to the view ( this is doubtful ).

The role of Serializer should be over at this point.


2 Views View

Serializer gives the successfully verified data to views. After views get the data, they use it toEndurance

2.1 create() and perform_create() in views

In views, you can override create() and get the data passed from the front end and verified by Serializer rules through request.GET/request.POS/request.data.
What happens after you get it? You can process this data again, or use it as an input parameter for calling other interfaces ( this is the legendary secondary encapsulation of interfaces of other systems ).
There is a huge difference between create() in the view and create() in the serializer:create() in the view can call perform_create() for persistence. This is great, because back-end development simply means adding, deleting, modifying, and querying the database (leaving aside the differences in using different frameworks), and the difficulty of adding, deleting, modifying, and querying actually depends on the problem you want to solve, that is, the actual specific business Complexity.


3 To summarize

  • Serializer mainly deals with the front end, so based on this, you rewrite Serializer's create(), essentially tofilter. If it passes the verification and meets your requirements, it will go to the view for next step processing ( filtering ); otherwise, some prompt information will be fed back to the front end (filtered).
  • Views, on the contrary, mainly deal with the backend. You override the create() of Views, essentially toEndurance. Before persisting, you can do any actual processing of the input parameters (including calling other interfaces), but because it is POST/create(), you still have to persist (perform_create()) in the end.

that's all .

Guess you like

Origin blog.csdn.net/qq_42774234/article/details/132170068
Recommended