序列化器

  • 参考网址
    https://blog.csdn.net/weixin_35688430/article/details/111203136

  • 定义序列化器

# models
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)
......
# serializer
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)
    image = serializers.ImageField(label='图片', required=False)

- 注意事项: serializer不是只能为数据库模型类定义,也可以为非数据库模型类的数据定义
  **serializer是独立于数据库之外的存在
  • 重要参数
- read_only   表明该字段仅用于序列化输出,默认False

- write_only  表明该字段仅用于反序列化输入,默认False

创建Serializer对象

Serializer(instance=None, data=empty, **kwarg)

- 用于序列化时,将模型类对象传入instance参数

- 用于反序列化时,将要被反序列化的数据传入data参数

- 除了instance和data参数外,在构造Serializer对象时,还可通过context参数额外添加数据
  通过context参数附加的数据,可以通过Serializer对象的context属性获取。

serializer = AccountSerializer(account, context={'request': request})

  • 序列化器的使用
- 序列化器的使用分两个阶段:

    - 在客户端请求时,使用序列化器可以完成对数据的反序列化
      即把json转成python dict类型,后端处理数据

    - 在服务器响应时,使用序列化器可以完成对数据的序列化
      即把python dict类型转成json,返回给前端
  • 序列化
- 先查询出一个图书对象

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

- 构造序列化器对象

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

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

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

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

book_qs = BookInfo.objects.all()
serializer = BookInfoSerializer(book_qs, many=True)
serializer.data
# [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')])]

  • 反序列化: 首先是数据校验
- 进行反序列化时,需要对数据进行验证后,才能获取验证成功的数据或保存成模型类对象

- 调用**is_valid()**方法进行验证,验证成功返回True,否则返回False

    - 验证失败,可以通过序列化器对象的errors属性获取错误信息,返回字典,包含了字段和字段的错误
      如果是非字段错误,可以通过修改REST framework配置中的NON_FIELD_ERRORS_KEY来控制错误字典中的键名

    - 验证成功,可以通过序列化器对象的validated_data属性获取数据
  • 在定义序列化器时,指明每个字段的序列化类型和选项参数,本身就是一种验证行为
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)
    image = serializers.ImageField(label='图片', required=False)
......

from booktest.serializers import BookInfoSerializer
data = {'bpub_date': 123}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # 返回False
serializer.errors
>>># {'btitle': [ErrorDetail(string='This field is required.', code='required')], 'bpub_date': [ErrorDetail(string='Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].', code='invalid')]}
>>>serializer.validated_data  # {}

data = {'btitle': 'python'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # True
serializer.errors  # {}
>>>serializer.validated_data  #  OrderedDict([('btitle', 'python')])

  • is_valid() 支持在校验失败的时候,直接抛异常,通过传递raise_exception=True参数开启
# Return a 400 response if the data was invalid.
serializer.is_valid(raise_exception=True)

自定义验证有三种方法

  • validate_field钩子(注意,不要写成 validated_field)
    钩子的意味着方法名称一定要写死,写固定的,错一个字符都不会被调用!
class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    ...

    def validate_btitle(self, value): # value就是用户传入的值
        if 'django' not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value # 校验无误,就返回value
......
from booktest.serializers import BookInfoSerializer
data = {'btitle': 'python'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # False   
serializer.errors
#  {'btitle': [ErrorDetail(string='图书不是关于Django的', code='invalid')]}


  • validate()方法: 多个字段一起校验
class BookInfoSerializer(serializers.Serializer):
    """图书数据序列化器"""
    ...

    def validate(self, attrs): # attrs是一个字典,包含用户输入的值
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if bread < bcomment:
            raise serializers.ValidationError('阅读量小于评论量')
        return attrs # 校验无误,返回字段
......

from booktest.serializers import BookInfoSerializer
data = {'btitle': 'about django', 'bread': 10, 'bcomment': 20}
s = BookInfoSerializer(data=data)
s.is_valid()  # False
>>>s.errors
#  {'non_field_errors': [ErrorDetail(string='阅读量小于评论量', code='invalid')]}

  • validators选项参数,可以对单个字段进行校验(支持多个验证)
def about_django(value):
    if 'django' not in value.lower():
        raise serializers.ValidationError("图书不是关于Django的")

class BookInfoSerializer(serializers.Serializer):
    ......                                                      # 支持传入多个函数验证对象
    btitle = serializers.CharField(label='名称', max_length=20, validators=[about_django])
......
from booktest.serializers import BookInfoSerializer
data = {'btitle': 'python'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # False   
serializer.errors
#  {'btitle': [ErrorDetail(string='图书不是关于Django的', code='invalid')]}
  • 还有一个 extra_kwargs 配置项也可以作验证
class RegisterSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(write_only=True, label='重复密码')
    sms_code = serializers.CharField(write_only=True, label='短信验证码')
    allow = serializers.CharField(write_only=True, label='是否同意协议')
    token = serializers.CharField(read_only=True, label='token')

    class Meta:
        model = UserInfo
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow','token']
        extra_kwargs = {  # 修改字段选项(作基本的校验)
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的用户名',
                    'max_length': '仅允许8-20个字符的用户名',
                }
            },
        }

反序列化-保存数据

  • 数据校验成功后,可以使用序列化器来完成数据反序列化的过程(把数据转成模型类对象,存入db/更新db)
    可以通过实现create()和update()两个方法来实现
class BookInfoSerializer(serializers.Serializer):
    ......
    def create(self, validated_data):
        # 这里为什么可以直接存?因为前面已经调用 is_valid(),数据校验无误了
        return BookInfo(**validated_data)

    def update(self, instance, validated_data):
        """更新,instance为要更新的对象实例,校验过的数据,从validated_data取即可"""
        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)
        return instance # 最后返回更新过的实例
  • 如果需要在返回数据对象的时候,也将数据保存到数据库中,可以这么搞
class BookInfoSerializer(serializers.Serializer):
    ......
    def create(self, validated_data):
        # return BookInfo(**validated_data)
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        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.save() # 调用save()方法存入db
        return instance
......
- 实现了上述两个方法后,在反序列化数据的时候,就可以通过save()方法返回一个模型实例
book = serializer.save()
  • 如果创建序列化器对象的时候,没有传递instance实例,则调用save()方法的时候,create()被调用
    相反,如果传递了instance实例,则调用save()方法的时候,update()被调用
    简而言之,有传instance,就是更新,自动调用update;
    没有传递instance,就是创建,自动调用create;
# 通过save(),把数据存入db
Copyfrom db.serializers import BookInfoSerializer
data = {'btitle': '封神演义'}
serializer = BookInfoSerializer(data=data) # 没有传递instance,则调用save()方法的时候,create()被调用
serializer.is_valid()  # True
serializer.save()  # <BookInfo: 封神演义>

# 通过save(),更新db数据
from db.models import BookInfo
book = BookInfo.objects.get(id=2)
data = {'btitle': '倚天剑'}
serializer = BookInfoSerializer(book, data=data) # 传递了instance,则调用save()方法的时候,update()被调用
serializer.is_valid()  # True
serializer.save()  # <BookInfo: 倚天剑>
book.btitle  # '倚天剑'

附加说明

  • 在对序列化器进行save()保存时,可以额外传递数据
    这些数据可以在create()和update()中的validated_data参数获取到
serializer.save(owner=request.user)
  • 默认序列化器必须传递所有required的字段,否则会抛出验证异常
    但是我们可以使用partial参数来允许部分字段更新
# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)

  • 如果继承了Serializer, 但凡是数据的新增还是更新, 调用 .save() 方法进行数据保存的时候都需要重写 create方法和 update方法, 如果继承的是ModelsSerializer则不需要重写

ModelSerializer组件

  • ModelSerializer与继承了Serializer,但提供了:

    • 基于模型类自动映射一系列字段
    • 基于模型类自动为Serializer生成validators,比如unique_together
    • 包含默认的create()和update()的实现
  • 定义

......
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo # 指明参照哪个模型类
        fields = '__all__' # 指明为模型类的哪些字段生成
......
>>> from booktest.serializers import BookInfoSerializer
>>> serializer = BookInfoSerializer()
>>> serializer
BookInfoSerializer():
    id = IntegerField(label='ID', read_only=True)
    btitle = CharField(label='名称', max_length=20)
    bpub_date = DateField(allow_null=True, label='发布日期', required=False)
    bread = IntegerField(label='阅读量', max_value=2147483647, min_value=-2147483648, required=False)
    bcomment = IntegerField(label='评论量', max_value=2147483647, min_value=-2147483648, required=False)
    image = ImageField(allow_null=True, label='图片', max_length=100, required=False)


指明字段

  • 使用fields来明确字段,__all__表名包含所有字段,也可以写明具体哪些字段,如
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ('id', 'btitle', 'bpub_date') # 指明只处理这个几个字段
......
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        exclude = ('image',) # 排除这个字段
......
class HeroInfoSerializer(serializers.ModelSerializer):
    hbook = BookInfoSerializer() # 显示指明字段(这里值是一个序列化器实例)
    class Meta:
        model = HeroInfo
        fields = ('id', ...... 'hbook') # 字段也要写进去
......
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ('id', ......)
        read_only_fields = ('id', 'bread', 'bcomment') # 这几个字段只用来输出(输入的时候不会再作校验)
......
# 我们可以使用extra_kwargs参数为ModelSerializer添加或修改原有的选项参数
class BookInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ('id',....... 'bread', 'bcomment')
        extra_kwargs = {
            'bread': {'min_value': 0, 'required': True},
            'bcomment': {'min_value': 0, 'required': True},
        }

BookInfoSerializer():
   id = IntegerField(label='ID', read_only=True)
   btitle = CharField(label='名称', max_length=20)
   bpub_date = DateField(allow_null=True, label='发布日期', required=False)
   # 生成的序列化实例字段,选项说明
   bread = IntegerField(label='阅读量', max_value=2147483647, min_value=0, required=True)
   bcomment = IntegerField(label='评论量', max_value=2147483647, min_value=0, required=True)

补充说明

souce参数: 想用哪个模型字段的值,就传入哪个(跨表用得多)

### models
from django.db import models


class Book(models.Model):

    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish_date = models.DateField()
    # 外键
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    # 多对多
    authors = models.ManyToManyField(to='Author')

    def __str__(self):
        return self.name


class Author(models.Model):

    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # 一对一
    author_datail = models.OneToOneField(to='AuthorDatail', unique=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class AuthorDatail(models.Model):

    telephone = models.CharField(max_length=11)
    birthday = models.DateField()
    address = models.CharField(max_length=128)

    def __str__(self):
        return self.telephone


class Publish(models.Model):

    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32, null=True)
    email = models.EmailField()

    def __str__(self):
        return self.name

### serializers
class BookInfoListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        # 序列化所有字段
        fields = '__all__'

### views
# 展示所有的图书信息
class BookInfoListView(ListAPIView):
    serializer_class = BookInfoListSerializer

    def get_queryset(self):
        queryset = Book.objects.all()
        return queryset

- 结果: publish/authors字段只展示数字ID(db存的就是数字)
  这样的结果回给前端,是不恰当的,应当展示具体的值

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish": 1,
        "authors": [
            1,
            2
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish": 4,
        "authors": [
            1
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish": 3,
        "authors": [
            3
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish": 2,
        "authors": []
    }
]
'''

- 可以这么干:

### serializers
class BookInfoListSerializer(serializers.ModelSerializer):
    # field.name跨表查询
    publish_name = serializers.CharField(source='publish.name')
    # 自定义模型方法:针对多对多字段
    authors_name = serializers.CharField(source='get_authors')
    class Meta:
        model = Book
        # fields = '__all__'
        fields = ['id','name','price','publish_date','publish_name','authors_name']

### models
class Book(models.Model):
    ......
    # 返回书籍的所有作者
    def get_authors(self):
        data_list = []
        queryset = self.authors.all()
        for obj in queryset:
            data_list.append(obj.name)
        return data_list

- 测试结果,很理想: http://127.0.0.1:8888/books/list/

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish_name": "福建出版社",
        "authors_name": "['张三', '李四']"
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish_name": "浙江出版社",
        "authors_name": "['张三']"
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish_name": "江西出版社",
        "authors_name": "['王五']"
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish_name": "江苏出版社",
        "authors_name": "['李四']"
    }
]
'''

  • 小结,source参数的三个作用
- 可以改字段名字: publish_name=serializers.CharField(source='publish')

- 可以跨表取值: publish_name = serializers.CharField(source='publish.name')

- 可以执行"模型方法": authors_name = serializers.CharField(source='get_authors') # get_authors是Book表模型中的方法

SerializerMethodField,用法和模型自定义方法类似

  • 一般用于跨表查询

  • 在序列化器内部写一个get_[外键名],会显示指定的数据(就是显示多张表的结果)

### serializers
class BookInfoListSerializer(serializers.ModelSerializer):
    # publish_name = serializers.CharField(source='publish.name')
    # 自定义 SerializerMethodField
    publish_name = serializers.SerializerMethodField()
    # authors_name = serializers.CharField(source='get_authors')
    authors_name = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ['id','name','price','publish_date','publish_name','authors_name']

    # get_xxx: 这里obj,就是Book模型对象
    def get_publish_name(self,obj):
        return obj.publish.name
    # 逻辑和上面的'自定义模型方法'类似: self.authors.all()
    def get_authors_name(self,obj):
        data_list = []
        queryset = obj.authors.all()
        for obj in queryset:
            data_list.append(obj.name)
        return data_list

- 测试结果: http://127.0.0.1:8888/books/list/

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish_name": "福建出版社",
        "authors_name": [
            "张三",
            "李四"
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish_name": "浙江出版社",
        "authors_name": [
            "张三"
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish_name": "江西出版社",
        "authors_name": [
            "王五"
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish_name": "江苏出版社",
        "authors_name": [
            "李四"
        ]
    }
]
'''

  • 还可以这么玩,使用 DictField 和 ListField(source='模型自定义方法')
### serializers
class BookInfoListSerializer(serializers.ModelSerializer):

    # 指定DictField,get_publish就只能返回dict格式的数据
    publish_name = serializers.DictField(source='get_publish')
    # authors_name = serializers.CharField(source='get_authors')
    # 指定ListField,get_authors就只能返回list格式的数据
    authors_name = serializers.ListField(source='get_authors')

    class Meta:
        model = Book
        fields = ['id','name','price','publish_date','publish_name','authors_name']

### models
class Book(models.Model):

    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish_date = models.DateField()
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')

    def __str__(self):
        return self.name

    # 返回list
    def get_authors(self):
        data_list = []
        queryset = self.authors.all()
        for obj in queryset:
            data_list.append(obj.name)
        return data_list

    # 返回dict
    def get_publish(self):
        return {
            'name':self.publish.name,
            'city':self.publish.city,
            'email':self.publish.email,
        }

- 测试结果: http://127.0.0.1:8888/books/list/

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish_name": {
            "name": "福建出版社",
            "city": "福州",
            "email": "fujian@sin.acom"
        },
        "authors_name": [
            "张三",
            "李四"
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish_name": {
            "name": "浙江出版社",
            "city": "杭州",
            "email": "zhejiang@sina.com"
        },
        "authors_name": [
            "张三"
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish_name": {
            "name": "江西出版社",
            "city": "南昌",
            "email": "jiangxi@sina.com"
        },
        "authors_name": [
            "王五"
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish_name": {
            "name": "江苏出版社",
            "city": "南京",
            "email": "jiangsu@sina.com"
        },
        "authors_name": [
            "李四"
        ]
    }
]
'''

depth介绍,跨表的层级

  • 不加depth,数据返回的结果是这样
### serializers
class BookInfoListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

- 测试结果: http://127.0.0.1:8888/books/list/
  结果不理想,外键字段只显示数字
'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish": 1,
        "authors": [
            1,
            2
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish": 4,
        "authors": [
            1
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish": 3,
        "authors": [
            3
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish": 2,
        "authors": [
            2
        ]
    }
]
'''

  • 加上depth,结果是这样,跨1层表的结果很理想
    authors的结果不理想
### serializers
class BookInfoListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Book
        fields = '__all__'
        # 增加这句
        depth = 1

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish": {
            "id": 1,
            "name": "福建出版社",
            "city": "福州",
            "email": "fujian@sin.acom"
        },
        "authors": [
            {
                "id": 1,
                "name": "张三",
                "age": 20,
                "author_datail": 1
            },
            {
                "id": 2,
                "name": "李四",
                "age": 22,
                "author_datail": 3
            }
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish": {
            "id": 4,
            "name": "浙江出版社",
            "city": "杭州",
            "email": "zhejiang@sina.com"
        },
        "authors": [
            {
                "id": 1,
                "name": "张三",
                "age": 20,
                "author_datail": 1
            }
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish": {
            "id": 3,
            "name": "江西出版社",
            "city": "南昌",
            "email": "jiangxi@sina.com"
        },
        "authors": [
            {
                "id": 3,
                "name": "王五",
                "age": 26,
                "author_datail": 2
            }
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish": {
            "id": 2,
            "name": "江苏出版社",
            "city": "南京",
            "email": "jiangsu@sina.com"
        },
        "authors": [
            {
                "id": 2,
                "name": "李四",
                "age": 22,
                "author_datail": 3
            }
        ]
    }
]
'''
  • 现在,把depth值调整为'2',结果也很理想(但是数据偏多...)
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_date": "2022-12-14",
        "publish": {
            "id": 1,
            "name": "福建出版社",
            "city": "福州",
            "email": "fujian@sin.acom"
        },
        "authors": [
            {
                "id": 1,
                "name": "张三",
                "age": 20,
                "author_datail": {
                    "id": 1,
                    "telephone": "18106951910",
                    "birthday": "1990-07-07",
                    "address": "厦门市思明区"
                }
            },
            {
                "id": 2,
                "name": "李四",
                "age": 22,
                "author_datail": {
                    "id": 3,
                    "telephone": "15265987452",
                    "birthday": "1995-02-22",
                    "address": "福州市鼓楼区"
                }
            }
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_date": "2023-01-01",
        "publish": {
            "id": 4,
            "name": "浙江出版社",
            "city": "杭州",
            "email": "zhejiang@sina.com"
        },
        "authors": [
            {
                "id": 1,
                "name": "张三",
                "age": 20,
                "author_datail": {
                    "id": 1,
                    "telephone": "18106951910",
                    "birthday": "1990-07-07",
                    "address": "厦门市思明区"
                }
            }
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_date": "2022-10-11",
        "publish": {
            "id": 3,
            "name": "江西出版社",
            "city": "南昌",
            "email": "jiangxi@sina.com"
        },
        "authors": [
            {
                "id": 3,
                "name": "王五",
                "age": 26,
                "author_datail": {
                    "id": 2,
                    "telephone": "15260581365",
                    "birthday": "1989-11-25",
                    "address": "漳州市芗城区"
                }
            }
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_date": "2020-01-01",
        "publish": {
            "id": 2,
            "name": "江苏出版社",
            "city": "南京",
            "email": "jiangsu@sina.com"
        },
        "authors": [
            {
                "id": 2,
                "name": "李四",
                "age": 22,
                "author_datail": {
                    "id": 3,
                    "telephone": "15265987452",
                    "birthday": "1995-02-22",
                    "address": "福州市鼓楼区"
                }
            }
        ]
    }
]

extra_kwargs: 修改字段的配置项(针对 ModelSerializer)

class BookInfoListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Book
        fields = '__all__'
        extra_kwargs = {
            'price':{'min_value':1,'required':True}
        }

使用子序列化器字段

- 需要创建一个子序列化类

- 子序列化类必须写在上方, 且只能对外键字段进行重写

- 使用了子序列化的外键字段就不能再进行反序列化过程(如果允许校验,要怎么写...)

- 子序列化单个数据需填写 many=False, 多个数据需填写 many=True

### serializers

# 自定义子序列化器
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ["name"]

class BookInfoListSerializer(serializers.ModelSerializer):

    publish_name = serializers.SerializerMethodField()
    # 创建子序列化器实例
    authors = AuthorSerializer(many=True)

    class Meta:
        model = Book
        fields = ['id','name','price','publish_name','authors']

    def get_publish_name(self,obj):
        return obj.publish.name

- 返回格式: 大list里面,包裹一个个字典对象

'''
[
    {
        "id": 1,
        "name": "十万个为什么",
        "price": "100.50",
        "publish_name": "福建出版社",
        "authors": [
            {
                "name": "张三"
            },
            {
                "name": "李四"
            }
        ]
    },
    {
        "id": 2,
        "name": "自然",
        "price": "80.88",
        "publish_name": "浙江出版社",
        "authors": [
            {
                "name": "张三"
            }
        ]
    },
    {
        "id": 3,
        "name": "英语学习",
        "price": "66.66",
        "publish_name": "江西出版社",
        "authors": [
            {
                "name": "王五"
            }
        ]
    },
    {
        "id": 4,
        "name": "钢铁是怎么炼成的",
        "price": "150.93",
        "publish_name": "江苏出版社",
        "authors": [
            {
                "name": "李四"
            }
        ]
    }
]
'''