1. Introduction
Hello, I’m Anguo!
Did you write an article about how to quickly get started with Django DRF
A quick introduction to Django DRF in 5 minutes
Next, several articles will explain the DRF model serialization, detailing the role, steps, and advanced uses of model serialization
2. What is the role of model serialization?
As a key step in DRF, model serialization has three main functions
-
Serialized data
Used to serialize the model into jSON-formatted objects for easy data return
-
Form validation
In the form request, it is used to verify that the data uploaded by the user meets the requirements of the project
-
Data manipulation
It can be used for data update, data creation, data saving, etc
3. Verify form fields
When specifying the fields to serialize, you can set the field type, default value, readable or writable, validate error messages, and so on, and then validate against the form fields
There are also three ways to verify form fields, respectively:
3-1 Serialized fields are specified in the form of parameters
For example, the field name data type is a string, max_length specifies the maximum length, and must be entered. Error_messages is used to set authentication failure messages
# Max length 50 # required=True: You must type # if not passed, an error is reported: Name = serializers.CharField(max_length=50, required=True, error_messages={"required": "name must be delivered "})Copy the code
3-2 Override the validate(self, attrs) method for validation
The attrs parameter contains all fields
We only need the custom validation logic, if verification is not through, throw exceptions “serializers. ValidationError.
For example, the validation name must contain the keyword “Shenzhen”, otherwise an exception will be thrown (indicating validation failure)
Def validate(self, attrs): """ def validate(self, attrs): """ print(attrs) if "" not in attrs.get("name"): Raise serializers. ValidationError (' name is not contained in the "shenzhen", authentication failed! ') return attrsCopy the code
3-3 Overwrite the validate_ field name (self,value) method
Validate against a field alone
We have to validate the name field, for example, if verification is not through, take the initiative to throw exceptions serializers. ValidationError
Def validate_name(self, name): """ def name: :return: """ if """ not in name: Raise serializers. ValidationError (' name is not contained in the "shenzhen", authentication failed! ') return nameCopy the code
4. Rewrite the create and update methods
The serialization classes you create inherit from the Serializers.Serializer class
Here we rewrite the update() and create() functions
Among them,
-
update( self, instance, validated_data )
To update data, update data from parameter VALIDATED_data to instance
-
create(self, validated_data)
Validated_data is used as the keyword argument to create the model
class GoodsSerializer(serializers.Serializer): Id = serializers.IntegerField(read_only=True) # error_messages: Name = serializers.CharField(max_length=200, required=True, error_messages={"required": }) def update(self, instance, validated_data): "" :param validated_data: :return: Instance. name = validated_data.get("name", Instance. save() return instance def create(self, validated_data): "" "" # Goods: objects. Create (**validated_data)Copy the code
5. The last
This chapter describes the steps of the normal serialization of the model. I will explain the process of model serialization, serialization nesting and project practice in the next article
If you think the article is good, please like, share, leave a message, because this will be my continuous output of more high-quality articles the strongest power!