当前位置:网站首页>DRF learning notes (II): Data deserialization
DRF learning notes (II): Data deserialization
2022-07-27 16:18:00 【fresh_ nam】
List of articles
Preface
This blog is written after the last blog , Sure Click here see
One 、 Data deserialization use
1、 Basic use
When deserializing with a serializer , You need to verify the data , To obtain the data that has been successfully verified or save it as a model class object .
Before getting the deserialized data , Must call is_valid() Method validation , Verification successful return True, Otherwise return to False.
Use :
>>> from demo.serializer import ClassInfoSerializer
>>> data = {
'number': ' One ', 'grade': ' Third grade '}
>>> serializer = ClassInfoSerializer(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{
'number': [ErrorDetail(string='A valid integer is required.', code='invalid')]}
2、 Custom validation
If you feel that the provided verification method is not enough , You can also customize the validation , There are three ways :
(1)validators
Add... To the field validators Option parameters , You can also supplement the verification behavior , Modify the code :
# Validation function
def about_grade(value):
if not (value == ' In grade one ' or value == ' second grade ' or value == ' Third grade '):
raise serializers.ValidationError(" Grade input error !")
class ClassInfoSerializer(serializers.Serializer):
""" Class data serializer """
id = serializers.IntegerField(label='ID', read_only=True)
number = serializers.IntegerField(label=' Class number ', required=False)
grade = serializers.CharField(label=' grade ', max_length=3, required=False, validators=[about_grade])
studentinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # add to
Use :
>>> from demo.serializers import ClassInfoSerializer
>>> data = {
'grade': ' Fourth grade '}
>>> serializer = ClassInfoSerializer(data=data)
result 
(2)validate_<field_name>
Right <field_name> Field , You can also modify the code as follows :
class ClassInfoSerializer(serializers.Serializer):
""" Class data serializer """
id = serializers.IntegerField(label='ID', read_only=True)
number = serializers.IntegerField(label=' Class number ', required=False)
grade = serializers.CharField(label=' grade ', max_length=3, required=False)
studentinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # add to
def validate_grade(self, value):
if not (value == ' In grade one ' or value == ' second grade ' or value == ' Third grade '):
raise serializers.ValidationError(" Grade input error !")
Use :
>>> from demo.serializers import ClassInfoSerializer
>>> data = {
'grade': ' Fourth grade '}
>>> serializer = ClassInfoSerializer(data=data)
result :
(3)validate
If you need to compare and verify multiple fields at the same time , Can define validate Method to verify , The code is modified as follows :
class ClassInfoSerializer(serializers.Serializer):
""" Class data serializer """
id = serializers.IntegerField(label='ID', read_only=True)
number = serializers.IntegerField(label=' Class number ', required=False)
grade = serializers.CharField(label=' grade ', max_length=3, required=False)
studentinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # add to
def validate(self, attrs):
number =attrs['number']
grade = attrs['grade']
if number > 10:
raise serializers.ValidationError("number Not greater than 10")
if not (grade == ' In grade one ' or grade == ' second grade ' or grade == ' Third grade '):
raise serializers.ValidationError(" Grade input error !")
Use :
(InteractiveConsole)
>>> from demo.serializers import ClassInfoSerializer
>>> data = {
'number': 11, 'grade': ' Fourth grade '}
>>> serializer = ClassInfoSerializer(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{
'non_field_errors': [ErrorDetail(string='number Not greater than 10', code='invalid')]}
>>> data = {
'number': 5, 'grade': ' Fourth grade '}
>>> serializer = ClassInfoSerializer(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{
'non_field_errors': [ErrorDetail(string=' Grade input error !', code='invalid')]}
Two 、 preservation
If after successful verification , Want to be based on validated_data Finish creating data object , By implementing create() and update() Two ways to achieve ( Add ). Add the following code :
def create(self, validated_data):
""" newly build """
return ClassInfo.objects.create(**validated_data)
def update(self, instance, validated_data):
""" to update ,instance For the object instance to be updated """
instance.number = validated_data.get('number', instance.number)
instance.grade = validated_data.get('grade', instance.grade)
instance.save()
return instance
After implementing the above two methods , When deserializing data , You can go through save() Method returns a data object instance .
If you create a serializer object , Pass on data Data time , Call save() Method time ,create() Called , contrary , If it's delivered instance example , Call save() Method time ,update() Called .
Use :
add to :
>>> from demo.serializers import ClassInfoSerializer
>>> data = {
'number': 2, 'grade': ' Third grade '}
>>> serializer = ClassInfoSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<ClassInfo: ClassInfo object (4)>
result :
stay navicat Data has indeed been added to view 
to update :
>>> from demo.models import ClassInfo
>>> Class_data = ClassInfo.objects.get(id=2)
>>> data = {
'number': 3, 'grade': ' Third grade '}
>>> serializer = ClassInfoSerializer(Class_data, data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<ClassInfo: ClassInfo object (2)>
result :
stay navicat The data has indeed been updated 
Next chapter :DRF Learning notes ( 3、 ... and ): Model class serializer ModelSerializer
边栏推荐
- 云管平台中租户以及多租户概念简单说明
- Flask连接mysql数据库已有表
- openwrt 增加RTC(MCP7940 I2C总线)驱动详解
- TSMC's counterattack: it accused lattice core of infringing 25 patents and asked for prohibition!
- Your password does not satisfy the current policy requirements (modify MySQL password policy setting simple password)
- Web test learning notes 01
- 时间序列-ARIMA模型
- 这些题~~
- 使用transform:translate()出现内容模糊问题
- Mlx90640 infrared thermal imager temperature sensor module development notes (VII)
猜你喜欢

Mlx90640 infrared thermal imager temperature sensor module development notes (VII)

Keil implements compilation with makefile

文本截取图片(哪吒之魔童降世壁纸)

判断数据的精确类型

DEX and AMMS of DFI security

解决MT7620不断循环uboot(LZMA ERROR 1 - must RESET board to recover)

Leetcode 226 flip binary tree (recursive)

: 0xC0000005: 写入位置 0x01458000 时发生访问冲突----待解

For enterprise operation and maintenance security, use the cloud housekeeper fortress machine!

渗透测试-干货 | 80篇+网络安全面试经验帖(面试篇)
随机推荐
Pychart imports the existing local installation package
ARIMA model selection and residuals
Text capture picture (Wallpaper of Nezha's demon child coming to the world)
Enable shallow and deep copies+
渗透测试-干货 | 80篇+网络安全面试经验帖(面试篇)
Makefile specifies the path of the library file loaded when the program runs
可载100人!马斯克发布史上最强“星际飞船” !最早明年上火星!
时间序列-ARIMA模型
实现浅拷贝和深拷贝+
Security software related to wireless network analysis (airtrack ng)
Excel extract duplicates
Openwrt 新增平台编译
单机高并发模型设计
To meet risc-v challenges? ARM CPU introduces custom instruction function!
新版jmeter函数助手不在选项菜单下-在工具栏中
Mlx90640 infrared thermal imager temperature sensor module development notes (VII)
Personal perception of project optimization
profileapi. h header
Vant UI toast and dialog use
JWT简介