序列化类常用字段和字段参数、序列化高级用法——source、序列化高级用法之定制字段的两种方式、 多表关联反序列化保存、序列化字段校验其他、ModelSerializer的使用
一、序列化类常用字段和字段参数
1.1 常用字段类
#1 BooleanField BooleanField()
#2 NullBooleanField NullBooleanField()
#3 CharField CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
#4 EmailField EmailField(max_length=None, min_length=None, allow_blank=False)
#5 RegexField RegexField(regex, max_length=None, min_length=None, allow_blank=False)
#6 SlugField SlugField(max_length=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+
#7 URLField URLField(max_length=200, min_length=None, allow_blank=False)
#8 UUIDField UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
#9 IPAddressField IPAddressField(protocol=’both’, unpack_ipv4=False, **options)
#10 IntegerField IntegerField(max_value=None, min_value=None)
#11 FloatField FloatField(max_value=None, min_value=None)
#12 DecimalField DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置
#13 DateTimeField DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
#14 DateField DateField(format=api_settings.DATE_FORMAT, input_formats=None)
#15 TimeField TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
#16 DurationField DurationField()
#17 ChoiceField ChoiceField(choices) choices与Django的用法相同
#18 MultipleChoiceField MultipleChoiceField(choices)
#19 FileField FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
#20 ImageField ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
----------重要-----------
ListField ListField(child=, min_length=None, max_length=None)
DictField DictField(child=)
#记住的:CharField IntegerField DecimalField DateTimeField BooleanField
ListField
DictField
1.2 常用字段参数
选项参数:
# CharField及其子类的(EmailField) ---》反序列化的校验,字段自己的规则
max_length 最大长度
min_lenght 最小长度
allow_blank 是否允许为空
trim_whitespace 是否截断空白字符
# IntegerField
max_value 最小值
min_value 最大值
# 所有字段类都有的
----重要-----
required 表明该字段在反序列化时必须输入,默认True
default 反序列化时使用的默认值
allow_null 表明该字段是否允许传入None,默认False
validators 该字段使用的验证器
----眼熟-----
error_messages 包含错误编号与错误信息的字典
label 用于HTML展示API页面时,显示的字段名称
help_text 用于HTML展示API页面时,显示的字段帮助提示信息
# 重点:
read_only 表明该字段仅用于序列化输出,默认False
write_only 表明该字段仅用于反序列化输入,默认False
## 反序列化校验执行流程
-1 先执行字段自己的校验规则----》最大长度,最小长度,是否为空,是否必填,最小数字。。。。
-2 validators=[方法,] ----》单独给这个字段加校验规则
name=serializers.CharField(validators=[方法,])
-3 局部钩子校验规则
-4 全局钩子校验规则
二、序列化高级用法——source
2.1 models
from django.db import models
# Create your models here.
# 创建关联表
class Book(models.Model):
name = models.CharField(max_length=32, verbose_name='书籍名')
price = models.CharField(max_length=32, verbose_name='价格')
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
author = models.ManyToManyField(to='Author')
class Publish(models.Model):
name = models.CharField(max_length=32,verbose_name='出版社')
addr = models.CharField(max_length=32,verbose_name='出版社地址')
class Author(models.Model):
name = models.CharField(max_length=32, verbose_name='作者')
phone = models.CharField(max_length=32, verbose_name='作者电话')
2.2 序列化定制字段名字
# source可以指定序列化字段的名字
# 自有的字段,直接写字段名字即可
# 关联字段,一对多的关联,直接点即可
# 多对多的关联,source使用不了
# coding:utf-8
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
# 字段参数,通用的,所有字段都可以写,通过source指定那个字段
# 自由字段,直接写字段名字即可
name_real = serializers.CharField(max_length=32, source='name')
price_real = serializers.CharField(max_length=32, source='price')
# 关联字段,一对多的关联,直接点即可
publish = serializers.CharField(source='publish.name')
# 多对多的关联,source使用不了
# authors = serializers.CharField(source='author.all')
三、序列化高级用法之定制字段的两种方式
3.1 SerializerMethodField定制
# 定制关联字段的显示形式
# 一对多,显示字典
# 多对多,显示列表套字典
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
name = serializers.CharField(max_length=8)
price = serializers.CharField(max_length=8)
# 定制返回格式--->方式一
publish_detail = serializers.SerializerMethodField()
def get_publish_detail(self, obj):
return {'name': obj.publish.name, 'addr': obj.publish.addr}
author_list = serializers.SerializerMethodField()
def get_author_list(self, obj):
author_list = []
for author in obj.author.all():
author_list.append({'name': author.name, 'phone': author.phone})
return author_list
3.2 在表模型中定制
3.2.1 models
class Book(models.Model):
name = models.CharField(max_length=32, verbose_name='书籍名')
price = models.CharField(max_length=32, verbose_name='价格')
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
author = models.ManyToManyField(to='Author')
def publish_detail(self):
return {'name': self.publish.name, 'addr': self.publish.addr}
def author_list(self):
authors_list = []
for author in self.author.all():
authors_list.append({'name': author.name, 'phone': author.phone})
return authors_list
3.2.2 serializer
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
name = serializers.CharField(max_length=8)
price = serializers.CharField(max_length=8)
# 这里的变量名要和models里面函数名一致
publish_detail = serializers.DictField()
author_list = serializers.ListField()
四、 多表关联反序列化保存
4.1 新增图书接口
# 新增图书接口
# 前端传入的数据格式:{"name": "红楼梦", "price": 99, "publish": 2, "author": [2,5]}
4.1.2 views (视图类)
from rest_framework.views import APIView
from .serializer import BookSerializer
from rest_framework.response import Response
class BookView(APIView):
def post(self, request):
ser = BookSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100,
'msg': '新增成功',
})
else:
return Response({'code': 101,
'msg': ser.errors
})
4.1.3 serializer(序列化类)
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.Serializer):
# name和price,既需要用来序列化,也需要用来反序列化,
# 既需要读,也需要写,所以不用夹read_only、write_only
name = serializers.CharField(max_length=8)
price = serializers.CharField(max_length=8)
# 只用来做反序列化 只读 read_only
publish_detail = serializers.DictField(read_only=True)
author_list = serializers.ListField(read_only=True)
# 只用来做序列化 只写 write_only
publish = serializers.CharField(write_only=True)
author = serializers.ListField(write_only=True)
# 新增需要重写create方法
def create(self, validated_data):
# validated_data 校验过后的数据,
# {"name": "红楼梦", "price": 99, "publish": 2, "author": [2,5]}
# 新增一本图书
book = Book.objects.create(name=validated_data.get('name'),
price=validated_data.get('price'),
publish_id=validated_data.get('publish')
)
# 作者也要关联上
# book.author
# 四种方法:add, remove, set, clear
book.author.add(*validated_data.get('author'))
return book
4.2 修改图书接口
# 修改图书接口
# 前端传入的数据格式:{"name": "红楼梦", "price": 99, "publish": 2, "author": [2,5]}
4.2.1 视图类
from rest_framework.views import APIView
from .models import Book, Publish, Author
from .serializer import BookSerializer
from rest_framework.response import Response
class BookDetailView(APIView):
def put(self,request, pk):
book = Book.objects.filter(pk=pk).first()
ser = BookSerializer(data=request.data, instance=book)
if ser.is_valid():
ser.save()
return Response({'code': 100,
'msg': '修改成功'
})
else:
return Response({'code': 101,
'msg': ser.errors
})
4.2.2 序列化类
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
name = serializers.CharField(max_length=8)
price = serializers.CharField(max_length=8)
# 只用来做反序列化, 只写
publish = serializers.CharField(write_only=True)
author = serializers.ListField(write_only=True)
# 修改需要重写update
def update(self, instance, validated_data):
# instance需要修改的数据、validated_data校验过后的数据
instance.name = validated_data.get('name')
instance.price = validated_data.get('price')
# 这里要根据出版社的id修改
instance.publish_id = validated_data.get('publish')
print(validated_data.get('publish'))
# 因为author传过来的是一个列表,所以需要先清空
# 先清空原来的数据,然后修改
instance.author.clear()
# 因为传过来的是一个列表,所以需要打散
author = validated_data.get('author')
instance.author.add(*author)
instance.save()
return instance
4.2.3 路由配置
from django.contrib import admin
from django.urls import path
from books import views
urlpatterns = [
path('books/<int:pk>', views.BookDetailView.as_view()),
]
五、反序列化字段校验其他
# 4中方法
-1 字段自己的:举例:name = serializers.CharField(max_length=8, error_messages={'max_length': '太长了'})
-2 validators=[方法,] 忽略掉
-3 局部钩子
-4 全局钩子
六、 ModelSerializer的使用
# ModelSerializer 继承Serializer
# 和表模型强关联
# 大部分请求,不用写create和update
6.1 serializer类
from rest_framework import serializers
from .models import Book
from rest_framework.validators import ValidationError
class BookSerializer(serializers.ModelSerializer):
# 跟表有关联
class Mate:
# 把model和Book表绑定
model = Book
# fields = '__all__'
# 这个魔法方法将Book表中的所有字段全部序列化了
# id name price publish author
# 序列化所有book中的字段
fields = ['name', 'price', 'publish', 'author',
'publish_detail', 'author_list'
]
# 定制name反序列化是,最长不能超过8,
# 给字段类加属性 --->方式1
extra_kwargs = {'name': {'max_length': 8},
'publish': {'write_only': True},
'author': {'write_only': True},
'publish_detail': {'read_only': True},
'author_list': {'read_only': True}
}
# 如果Meta写了__all__ ,就相当于,复制了表模型中的所有字段,放在了这里,做了个映射
# name = serializers.CharField(max_length=32)
# price = serializers.CharField(max_length=32)
# 定制name反序列化时,最长不能超过8 给字段类加属性---方式二,重写name字段
# name = serializers.CharField(max_length=8)
# 同理,所有的read_only和wirte_only都可以通过重写或使用extra_kwargs传入
# 终极,把这个序列化类写成跟之前一模一样项目
# publish_detail = serializers.SerializerMethodField(read_only=True)
# def get_publish_detail(self, obj):
# return {'name': obj.publish.name, 'addr': obj.publish.addr}
# author_list = serializers.SerializerMethodField(read_only=True)
# def get_author_list(self, obj):
# l = []
# for author in obj.authors.all():
# l.append({'name': author.name, 'phone': author.phone})
# return l
#局部钩子和全局钩子跟之前完全一样
def validate_name(self, name):
if name.startswith('sb'):
raise ValidationError('不能以sb开头')
else:
return name
标签:serializers,name,author,max,用法,length,多表,序列化
From: https://www.cnblogs.com/HaiMan/p/17087522.html