1. [
  1. 课程介绍
  2. ](_index_)
    1. [
  1. 引入DjangoRESTframework
  2. ](c01-introducetodrf_index)
  3. -
  4. [
  5. Web应用模式
  6. ](c01-introducetodrf_separatedfrontendandbackend)
    1. [
  1. 认识RESTful
  2. ](c01-introducetodrf_introducetorest)
    1. [
  1. RESTful设计方法
  2. ](c01-introducetodrf_howtodesignrest)
    1. [
  1. 使用Django开发REST接口
  2. ](c01-introducetodrf_developrestapiwithdjango)
    1. [
  1. 明确REST接口开发的核心任务
  2. ](c01-introducetodrf_coretasktodeveloprestapi)
    1. [
  1. DjangoRESTframework简介
  2. ](c01-introducetodrf_aboutdrf)
    1. [
  1. DRF工程搭建
  2. ](c02-drfproject_index)
  3. -
  4. [
  5. 环境安装与配置
  6. ](c02-drfproject_installandconfig)
    1. [
  1. 见识DRF的魅力
  2. ](c02-drfproject_thefirstdrfprogram)
    1. [
  1. Serializer序列化器
  2. ](c03-serializer_index)
  3. -
  4. [
  5. 定义Serializer
  6. ](c03-serializer_declaring)
    1. [
  1. 序列化使用
  2. ](c03-serializer_serializing)
    1. [
  1. 反序列化使用
  2. ](c03-serializer_deserializing)
    1. [
  1. 模型类序列化器ModelSerializer
  2. ](c03-serializer_modelserializer)
    1. [
  1. 视图
  2. ](c04-view_index)
  3. -
  4. [
  5. RequestResponse
  6. ](c04-view_requestandresponse)
    1. [
  1. 视图概览
  2. ](c04-view_view)
    1. [
  1. 视图说明
  2. ](c04-view_viewintroduction)
    1. [
  1. 视图集ViewSet
  2. ](c04-view_viewset)
    1. [
  1. 路由Router
  2. ](c04-view_routers)
    1. [
  1. 其他功能
  2. ](c05-components_index)
  3. -
  4. [
  5. 认证
  6. ](c05-components_authentication)
    1. [
  1. 权限
  2. ](c05-components_permissions)
    1. [
  1. 限流
  2. ](c05-components_throttling)
    1. [
  1. 过滤
  2. ](c05-components_filtering)
    1. [
  1. 排序
  2. ](c05-components_ordering)
    1. [
  1. 分页
  2. ](c05-components_pagination)
    1. [
  1. 版本
  2. ](c05-components_versioning)
    1. [
  1. 异常处理
  2. ](c05-components_exceptions)
    1. [
  1. 自动生成接口文档
  2. ](c05-components_documents)
    1. [
    2. Published with GitBook
    3. ](https://www.gitbook.com)

课程介绍

序列化使用

我们在django shell中来学习序列化器的使用。

  1. python manage.py shell

1 基本使用

1) 先查询出一个图书对象

  1. from booktest.models import BookInfo
  2. book = BookInfo.objects.get(id=2)

2) 构造序列化器对象

  1. from booktest.serializers import BookInfoSerializer
  2. serializer = BookInfoSerializer(book)

3)获取序列化数据
通过data属性可以获取序列化后的数据

  1. serializer.data
  2. # {'id': 2, 'btitle': '天龙八部', 'bpub_date': '1986-07-24', 'bread': 36, 'bcomment': 40, 'image': None}

4)如果要被序列化的是包含多条数据的查询集QuerySet,可以通过添加many=True参数补充说明

  1. book_qs = BookInfo.objects.all()
  2. serializer = BookInfoSerializer(book_qs, many=True)
  3. serializer.data
  4. # [OrderedDict([('id', 2), ('btitle', '天龙八部'), ('bpub_date', '1986-07-24'), ('bread', 36), ('bcomment', 40), ('image', N]), OrderedDict([('id', 3), ('btitle', '笑傲江湖'), ('bpub_date', '1995-12-24'), ('bread', 20), ('bcomment', 80), ('image'ne)]), OrderedDict([('id', 4), ('btitle', '雪山飞狐'), ('bpub_date', '1987-11-11'), ('bread', 58), ('bcomment', 24), ('ima None)]), OrderedDict([('id', 5), ('btitle', '西游记'), ('bpub_date', '1988-01-01'), ('bread', 10), ('bcomment', 10), ('im', 'booktest/xiyouji.png')])]

2 关联对象嵌套序列化

如果需要序列化的数据中包含有其他关联对象,则对关联对象数据的序列化需要指明。
例如,在定义英雄数据的序列化器时,外键hbook(即所属的图书)字段如何序列化?
我们先定义HeroInfoSerialzier除外键字段外的其他部分

  1. class HeroInfoSerializer(serializers.Serializer):
  2. """英雄数据序列化器"""
  3. GENDER_CHOICES = (
  4. (0, 'male'),
  5. (1, 'female')
  6. )
  7. id = serializers.IntegerField(label='ID', read_only=True)
  8. hname = serializers.CharField(label='名字', max_length=20)
  9. hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
  10. hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)

对于关联字段,可以采用以下几种方式:

1) PrimaryKeyRelatedField

此字段将被序列化为关联对象的主键。

  1. hbook = serializers.PrimaryKeyRelatedField(label='图书', read_only=True)
  2. hbook = serializers.PrimaryKeyRelatedField(label='图书', queryset=BookInfo.objects.all())

指明字段时需要包含read_only=True或者queryset参数:

  • 包含read_only=True参数时,该字段将不能用作反序列化使用
  • 包含queryset参数时,将被用作反序列化时参数校验使用

使用效果:

  1. from booktest.serializers import HeroInfoSerializer
  2. from booktest.models import HeroInfo
  3. hero = HeroInfo.objects.get(id=6)
  4. serializer = HeroInfoSerializer(hero)
  5. serializer.data
  6. # {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': 2}

2)使用关联对象的序列化器

  1. hbook = BookInfoSerializer()

使用效果

  1. {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': OrderedDict([('id', 2), ('btitle', '天龙八部')te', '1986-07-24'), ('bread', 36), ('bcomment', 40), ('image', None)])}

3) StringRelatedField

此字段将被序列化为关联对象的字符串表示方式(即str方法的返回值)

  1. hbook = serializers.StringRelatedField(label='图书')

使用效果

  1. {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': '天龙八部'}

4)HyperlinkedRelatedField

此字段将被序列化为获取关联对象数据的接口链接

  1. hbook = serializers.HyperlinkedRelatedField(label='图书', read_only=True, view_name='books-detail')

必须指明view_name参数,以便DRF根据视图名称寻找路由,进而拼接成完整URL。
使用效果

  1. {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': 'http://127.0.0.1:8000/books/2/'}

我们暂时还没有定义视图,此方式不再演示。

5)SlugRelatedField

此字段将被序列化为关联对象的指定字段数据

  1. hbook = serializers.SlugRelatedField(label='图书', read_only=True, slug_field='bpub_date')

slug_field指明使用关联对象的哪个字段
使用效果

  1. {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': datetime.date(1986, 7, 24)}

6) 重写to_representation方法

序列化器的每个字段实际都是由该字段类型的to_representation方法决定格式的,可以通过重写该方法来决定格式。
注意,to_representations方法不仅局限在控制关联对象格式上,适用于各个序列化器字段类型。
自定义一个新的关联字段:

  1. class BookRelateField(serializers.RelatedField):
  2. """自定义用于处理图书的字段"""
  3. def to_representation(self, value):
  4. return 'Book: %d %s' % (value.id, value.btitle)

指明hbook为BookRelateField类型

  1. hbook = BookRelateField(read_only=True)

使用效果

  1. {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': 'Book: 2 天龙八部'}

3 many参数

如果关联的对象数据不是只有一个,而是包含多个数据,如想序列化图书BookInfo数据,每个BookInfo对象关联的英雄HeroInfo对象可能有多个,此时关联字段类型的指明仍可使用上述几种方式,只是在声明关联字段时,多补充一个many=True参数即可。
此处仅拿PrimaryKeyRelatedField类型来举例,其他相同。
在BookInfoSerializer中添加关联字段:

  1. class BookInfoSerializer(serializers.Serializer):
  2. """图书数据序列化器"""
  3. id = serializers.IntegerField(label='ID', read_only=True)
  4. btitle = serializers.CharField(label='名称', max_length=20)
  5. bpub_date = serializers.DateField(label='发布日期', required=False)
  6. bread = serializers.IntegerField(label='阅读量', required=False)
  7. bcomment = serializers.IntegerField(label='评论量', required=False)
  8. image = serializers.ImageField(label='图片', required=False)
  9. heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) # 新增

使用效果:

  1. from booktest.serializers import BookInfoSerializer
  2. from booktest.models import BookInfo
  3. book = BookInfo.objects.get(id=2)
  4. serializer = BookInfoSerializer(book)
  5. serializer.data
  6. # {'id': 2, 'btitle': '天龙八部', 'bpub_date': '1986-07-24', 'bread': 36, 'bcomment': 40, 'image': None, 'heroinfo_set': [6,8, 9]}