DRF框架之Serializer序列化器的序列化和反序列化操作
DRF 序列化 和 反序列化
转载自:https://blog.csdn.net/qq_42517220/article/details/94441021
序列化
定义
序列化:将model模型对象转换为json格式的字符串,我们可以对返回的数据进行过滤(一般是后端构造数据,返回给前端)
继承说明:Django REST framework中的Serializer使用类来定义,须继承自
rest_framework.serializers.Serializer
或
rest_framework.serializers.ModelSerializer
Serializers使用方式
例如,我们已有了一个数据库模型类BookInfo
class BookInfo(models.Model):
btitle = models.CharField(max_length=20, verbose_name='名称')
bpub_date = models.DateField(verbose_name='发布日期', null=True)
bread = models.IntegerField(default=0, verbose_name='阅读量')
bcomment = models.IntegerField(default=0, verbose_name='评论量')
image = models.ImageField(upload_to='booktest', verbose_name='图片', null=True)
我们想为这个模型类提供一个序列化器,在应用中models.py同级目录创建serializers.py文件,定义内容如下:
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
logo = serializers.ImageField(label='图片', required=False)
在试图views.py文件中使用如下:
from django.views import View
from .models import BookInfo
from .serializers import BookInfoSerializer
class BookView(View):
def get(self, request, pk):
book = BookInfo.objects.get(pk=pk)
# 构建序列化对象,将模型对象传入,将其转换为json格式字符串
# 转换后的格式:{"id": 1, ....}, 键为serializers序列化器中定义的所有字段
serializer = BookInfoSerializer(book)
# 转换后的字符串对象保存在serializer的data属性中
return JsonResponse(serializer.data)
-
serializer序列化器说明:
-
BookInfoSerializer:默认只能接收单个对象,如果想要接收一个queryset对象,并对其进行转换,需要设定参数:many=True
from django.views import View from .models import BookInfo from .serializers import BookInfoSerializer class BookView(View): def get(self, request): books = BookInfo.objects.all() # 构建序列化对象,将模型对象传入,将其转换为json格式字符串 serializer = BookInfoSerializer(books, many=True) # 转换后的字符串对象保存在serializer的data属性中 # 转换后的格式:[{}, {}, ...], 内部字典数据同上,注意该数据并非json,仅仅是长得像json格式的字符串 return JsonResponse(serializer.data, safe=False)
注意:JsonResponse转换列表时需要给定参数:safe=False,否则会报错
序列化的高级使用
1、关联对象的序列化
PrimaryKeyRelatedField:返回关联对象的主键id
# models.py
from django.db import models
class BookInfo(models.Model):
btitle = models.CharField(max_length=128, verbose_name='书名')
pbublic_date = models.DateField(verbose_name='发布日期')
bread = models.IntegerField(default=0, verbose_name='阅读量')
bcomment = models.IntegerField(default=0, verbose_name='评论量')
is_delete = models.BooleanField(default=0, verbose_name='逻辑删除')
logo = models.ImageField(upload_to='booktest', verbose_name='封面图', null=True)
class Meta:
db_table = 'tb_books'
verbose_name = '图书'
verbose_name_plural = verbose_name
def __str__(self):
return self.btitle
class HeroInfo(models.Model):
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
hname = models.CharField(max_length=36, verbose_name='名字')
hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
hcomment = models.CharField(max_length=200, null=True, verbose_name='描述信息')
hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='图书')
class Meta:
db_table = 'tb_heros'
verbose_name = '英雄'
verbose_name_plural = verbose_name
def __str__(self):
return self.hname
# serializer.py
from rest_framework import serializers
from books.models import BookInfo
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
# 英雄关联到的书籍对象,此处必须指定关联到的对象queryset或者指定参数 read_only=True
# hbook = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())
hbook = serializers.PrimaryKeyRelatedField(read_only=True)
# views.py
class HeroView(View):
def get(self, request, pk):
hero = HeroInfo.objects.get(pk=pk)
seralizer = HeroInfoSerializer(hero)
return JsonResponse(seralizer.data)
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('heros/<hid>', views.HeroView.as_view()),
]
# http://127.0.0.1:8000/heros/5
{
id: 5,
hname: "贾宝玉",
hgender: 0,
hcomment: null,
hbook: 1
}
StringRelatedField:返回关联对象模型类中定义的__str__方法返回值
serializers.py
from rest_framework import serializers
from books.models import BookInfo
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
# 返回关联对象模型类中定义的__str__方法返回值
# 为什么此处不需要指定read_only=True,因为此方法内部自己将其封装进去了
"""
class StringRelatedField(RelatedField):
def __init__(self, **kwargs):
kwargs['read_only'] = True
super(StringRelatedField, self).__init__(**kwargs)
def to_representation(self, value):
return six.text_type(value)
"""
hbook = serializers.StringRelatedField()
{
id: 5,
hname: "贾宝玉",
hgender: 0,
hcomment: null,
hbook: "红楼梦"
}
SlugRelatedField:显示关联对象的某一个字段
serializers.py
from rest_framework import serializers
from books.models import BookInfo
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
# 显示关联对象pbublic_date字段值
hbook = serializers.SlugRelatedField(label='图书', read_only=True, slug_field='pbublic_date')
{
id: 5,
hname: "贾宝玉",
hgender: 0,
hcomment: null,
hbook: "1971-07-01"
}
使用关联对象的序列化器
serializers.py
from rest_framework import serializers
from books.models import BookInfo
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
# 显示关联对象的序列化后的数据
hbook = BookInfoSerializer()
{
id: 5,
hname: "贾宝玉",
hgender: 0,
hcomment: null,
hbook: {
id: 1,
btitle: "红楼梦",
bread: 0,
bcomment: 0,
logo: null
}
}
重写to_representation方法
序列化器的每个字段实际都是由该字段类型的to_representation方法决定格式的,可以通过重写该方法来决定格式
注意,to_representations方法不仅局限在控制关联对象格式上,适用于各个序列化器字段类型。
自定义一个新的关联字段:
# serializers.py
from rest_framework import serializers
from books.models import BookInfo
class BookRelateField(serializers.RelatedField):
"""自定义用于处理图书的字段"""
def to_representation(self, value):
return 'Book: %d %s' % (value.id, value.btitle)
指明hbook为BookRelateField类型
# serializer.py
from rest_framework import serializers
from books.models import BookInfo
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDE_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
# 显示我们上述自定义的类对象的返回值
hbook = BookRelateField(read_only=True)
# 使用效果
# http://127.0.0.1:8000/heros/5/
{
id: 5,
hname: "贾宝玉",
hgender: 0,
hcomment: null,
hbook: "Book: 1 红楼梦"
}
反向序列化(即从一到多:序列化书籍中的英雄对象)
# serializers.py
from rest_framework import serializers
from books.models import BookInfo
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
is_delete = serializers.BooleanField(write_only=True)
logo = serializers.ImageField(label='图片', required=False)
# 使用关联对象的序列化器,将书本反向关联的英雄序列化输出
# 注意 many=True,一定不能省略
heroinfo_set = HeroInfoSerializer(many=True)
{
id: 2,
btitle: "西游记",
bread: 0,
bcomment: 0,
logo: null,
heroinfo_set: [
{
id: 1,
hname: "孙悟空",
hgender: 0,
hcomment: null,
hbook: 2
},
{
id: 2,
hname: "猪八戒",
hgender: 0,
hcomment: null,
hbook: 2
},
{
id: 3,
hname: "沙悟净",
hgender: 0,
hcomment: null,
hbook: 2
},
{
id: 4,
hname: "唐僧",
hgender: 0,
hcomment: null,
hbook: 2
}
]
}
ModelSerializer(模型类序列化器)使用方式
功能同我们上述定义的序列化器,但更简单方便
from rest_framework import ModelSerializer
from .models import BookInfo
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
# 指要序列化的模型对象
model = BookInfo
# 列出要序列化的字段,格式为列表或元组, __all__代表序列化所有字段
fields = "__all__"
使用fields来明确字段,__all__表名包含所有字段,也可以写明具体哪些字段,如
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = ('id', 'btitle', 'bpub_date')
使用exclude可以明确排除掉哪些字段,注意:exclude和fields不能同时存在
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
exclude = ('logo',)
默认ModelSerializer使用主键作为关联字段,但是我们可以使用depth来简单的生成嵌套表示,depth应该是整数,表明嵌套的层级数量。如:现在有一个英雄model,与上述model是多对一关系(即一本书中会有多个英雄)
# models.py
from books import models
class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = models.IntegerField(label='ID', read_only=True)
hname = models.CharField(label='名字', max_length=20)
hgender = models.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = models.CharField(label='描述信息', max_length=200, required=False, allow_null=True)
book = models.ForeignKey(BookInfo, related_name='book')
class Meta:
db_table = 'tb_heros'
verbose_name = '英雄'
verbose_name_plural = verbose_name
def __str__(self):
return self.hname
# serializers.py
class HeroInfoSerializer(serializers.ModelSerializer):
class Meta:
model = HeroInfo
fields = '__all__'
depth = 1
# views.py
from booktest.serializers import HeroInfoSerializer
from booktest.models import HeroInfo
class HeroView(View):
def get(self, request, pk):
hero = HeroInfo.objects.get(id=6)
serializer = HeroInfoSerializer(hero)
print(serializer.data)
# 打印结果
{
'id': 6,
'hname': '乔峰',
'hgender': 1,
'hcomment': '降龙十八掌',
'hbook': {
'id': 2,
'btitle': '天龙八部',
'bpub_date': '1986-07-24',
'bread': 36,
'bcomment': 40,
'logo': None
}
}
指明只读字段:可以通过read_only_fields指明只读字段,即仅用于序列化输出的字段,在反序列化时不允许修改
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment')
read_only_fields = ('id', 'bread', 'bcomment')
指明只读字段:可以通过write_only_fields指明只写字段,即仅用于反序列化验证的字段,在序列化时不进行显示
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment')
write_only_fields = ('bread', 'bcomment')
我们可以使用extra_kwargs参数为ModelSerializer添加或修改原有的选项参数
比如在数据库声明时未指定字段的最大值与最小值,就可以通过该属性动态添加
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment')
extra_kwargs = {
'bread': {'min_value': 0, 'required': True}},
'bcomment': {'max_value': 0, 'required': True}},
}
反序列化
定义:
反序列化:将json格式的字符串转换为对象,我们可以对接收的数据进行校验(一般是后端接收前端传送的数据进行校验后进行数据库相关操作:增加、修改 serializer.save())
继承说明:Django REST framework中的Serializer使用类来定义,须继承自
rest_framework.serializers.Serializer
或
rest_framework.serializers.ModelSerializer
说明:序列化和反序列化使用同一序列化器,通过指定不同参数来区别是用于序列化还是反序列化
# 所有序列化器基类
class BaseSerializer(Field):
def __init__(self, instance=None, data=empty, **kwargs):
self.instance = instance
if data is not empty:
self.initial_data = data
self.partial = kwargs.pop('partial', False)
self._context = kwargs.pop('context', {})
kwargs.pop('many', None)
super(BaseSerializer, self).__init__(**kwargs)
当我们只传递一个参数时,且没有指明传递对象,按位置传参,则将book对象传递给instance,此时默认为进行序列化输出
# views.py
class BooksView(View):
def get(self, request, pk):
book = Book.objects.get(pk=pk)
# 构建序列化对象,将模型对象传入,将其转换为json格式字符串
# serializer = BookInfoSerializer(instance=book)
serializer = BookInfoSerializer(book)
创建对象
当我们传递一个参数并指名对象为data时,默认做反序列化验证,示意创建
# views.py
import json
from books.serializers import BookInfoSerializer
class BooksView(View):
def post(self, request):
# 获取前端传递的json数据
json_bytes = request.body # 默认或渠道字节类型数据
json_str = json_bytes.decode() # 将其转换为字符类型
book = json.loads(json_str) # 将json数据转换为字典
# 进行字段校验
serializer = BookInfoSerializer(data=book)
# 校验成功的数据保存在 serializer.validated_data 中,是一个有序字典对象
# print(serializer.validated_data)
# 判断校验是否成功,校验失败时抛出异常,终止往下执行
success = serializer.is_valid(raise_exception=True)
if success:
# 重点强调:此处save会调用序列化器中的create()方法,此方法需要我们自己定义实现
serializer.save()
# 我们也可以直接在此处进行保存操作
# BookInfo(**serializer.validated_data).save()
else:
print(serializer.error)
from rest_framework import serializers
from books.models import BookInfo
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
logo = serializers.ImageField(label='图片', required=False)
def create(self, validated_data):
# validated_data: 校验成功的数据
book_info = BookInfo(**validated_data).save()
# 重点强调,此处必须返回保存成功后的对象
return book_info
更新对象
接下来示意更新操作
# serializers.py
class BookView(View):
def put(self, request, pk):
try:
book = BookInfo.objects.get(pk=pk)
except Exception as e:
raise Http404
# 获取前端传递的json数据
json_bytes = request.body # 默认或渠道字节类型数据
json_str = json_bytes.decode() # 将其转换为字符类型
book_dict = json.loads(json_str) # 将json数据转换为字典
# 进行字段校验, 当instance和data同时传递时表示修改操作
# partial=True 表示前端并不需要将所有字段都传递回来,可以选择性传递要修改的字段
serializer = BookInfoSerializer(instance=book, data=book_dict, partial=True)
success = serializer.is_valid(raise_exception=True)
if success:
# 重点强调:此处save会调用序列化器中的update()方法,此方法需要我们自己定义实现
serializer.save()
return HttpResponse('update success')
# serializers.py
from rest_framework import serializers
from books.models import BookInfo
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
logo = serializers.ImageField(label='图片', required=False)
def create(self, validated_data):
# validated_data: 校验成功的数据
book_info = BookInfo(**validated_data).save()
# 重点强调,此处必须返回保存成功后的对象
return book_info
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
# 说明,当用户更新时,并不一定更新所有字段,所以,用户未传递过来进行更新的字段我们将其原有的数据进行填充
instance.btitle = validated_data.get('btitle', instance.btitle)
instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
instance.bread = validated_data.get('bread', instance.bread)
instance.bcomment = validated_data.get('bcomment', instance.bcomment)
instance.logo = validated_data.get('logo', instance.logo)
instance.save()
return instance
serializer.save()源码解析
def save(self, **kwargs):
validated_data = dict(
list(self.validated_data.items()) +
list(kwargs.items())
)
# self 即我们创建的序列化器的实例对象
# self.instance 即我们传递的对象
# serializer = BookInfoSerializer(data=book)
# 当我们传递了instance对象,则调用update方法进行数据更新
if self.instance is not None:
self.instance = self.update(self.instance, validated_data)
assert self.instance is not None, (
'`update()` did not return an object instance.'
)
# 当我们没有传递instance对象时,则调用create方法进行对象创建
else:
self.instance = self.create(validated_data)
assert self.instance is not None, (
'`create()` did not return an object instance.'
)
return self.instance
- 自定义校验
需求1:要求传递过来的书名必须包含 django,那么此时我们就必须自定义验证器
1
单独字段的验证器定义validate_<field_name>
# serializers.py
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
def validate_btitle(self, value):
# value:前端传递过来存储在字典中的数据
if 'django' not in value.lower():
raise serializers.ValidationError("图书不是关于Django的")
return value
需求2:提交的数据中阅读量必须大于评论量,否则不让提交,给出错误
1
同时对多个字段进行比较验证时,可以定义validate方法来验证
# serializers.py
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False)
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
def validate(self, attrs):
# attrs:前端传递过来存储在字典对象
bread = attrs['bread']
bcomment = attrs['bcomment']
if bread < bcomment:
raise serializers.ValidationError('阅读量小于评论量')
return attrs
需求3:要求传递过来的出版日期必须小于当前日期
1
通过validators参数自定义验证器函数
# serializers.py
from django.utils import timezone
from rest_framework import serializers
def bpub_date(value):
if value > timezone.now().date():
raise serializers.ValidationError("出版日期大于当前时间")
return value
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False, validators=[bpub_date])
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
UniqueValidator唯一性检验
# serializers.py
from django.utils import timezone
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
# 该字段不允许重复
btitle = serializers.CharField(label='名称', max_length=20, validators=[UniqueValidator])
bpub_date = serializers.DateField(label='发布日期', required=False, validators=[])
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
UniqueTogetherValidation联合唯一
# serializers.py
from django.utils import timezone
from rest_framework import serializers
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label='ID', read_only=True)
# 该字段不允许重复
btitle = serializers.CharField(label='名称', max_length=20)
bpub_date = serializers.DateField(label='发布日期', required=False, validators=[])
bread = serializers.IntegerField(label='阅读量', required=False)
bcomment = serializers.IntegerField(label='评论量', required=False)
class Meta:
# 要求书名和出版日期不能同时一致
validators = [
UniqueTogetherValidator(
fields=('btitle', 'bpub_date')
)
]