06.ModelSerializer

01.ModelSerializer

 

1.1 ModelSerializer特点

 

  • ModelSerializer是Serializer类的子类
  • 相对于Serializer,增加了以下功能:
    • 基于模型类字段自动生成序列化器类的字段
    • 包含默认的create()和update()方法的实现

 

1.2 定义ModelSerializer语法

 

from rest_framework import serializers

class BookInfoSerializer(serializers.ModelSerializer):
    """图书序列化器类"""
    class Meta:
        model = BookInfo
        fields = '__all__'
        # exclude = ('is_delete',)
        extra_kwargs = {
            'bread': {'min_value': 0, 'required': True},
            'bcomment': {'min_value': 0, 'required': True},
            'btitle': {'min_length': 3}
        }

 

1.3 查看自动生成字段

 

(django2.2) C:	mpdrf_demo>python manage.py shell -i ipython
In [1]: from book.serializers import BookInfoSerializer2
In [2]: book = BookInfoSerializer2()
In [3]: book
BookInfoSerializer2():
    id = IntegerField(label='ID', read_only=True)
    heroinfo_set = HeroInfoSerializer(many=True):
        id = IntegerField(label='ID', read_only=True)
        hname = CharField(label='名字', max_length=20)
        hgender = ChoiceField(choices=((0, ''), (1, '')), label='性别', required=False)
        hcomment = CharField(label='描述信息', max_length=200, required=False)
    btitle = CharField(label='名称', max_length=20)
    bpub_date = DateField(label='发布日期')
    bread = IntegerField(label='阅读量', required=False)
    bcomment = IntegerField(label='评论量', required=False)
    is_delete = BooleanField(label='逻辑删除', required=False)

 

02.ModelSerializer使用

 

2.1 book/serializers.py

 

# -*- coding: utf-8 -*-
from rest_framework import serializers
from book.models import BookInfo,HeroInfo

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

    class Meta:
        model = HeroInfo


class BookInfoSerializer2(serializers.ModelSerializer):
    # 字段名名, 必须是模型可以 . 引用到的变量
    # BookInfo().   "heroinfo_set"  才能作为字段名,  如果是集合, 需要加many=True,
    heroinfo_set = HeroInfoSerializer(many=True)   # 
    """图书序列化器类"""
    class Meta:
        model = BookInfo
        fields = '__all__'

 

2.2 查询结果

 

[
    {
        "id": 1,
        "heroinfo_set": [
            {
                "id": 1,
                "hname": "孙悟空",
                "hgender": 1,
                "hcomment": "七十二变"
            },
            {
                "id": 2,
                "hname": "猪八戒",
                "hgender": 1,
                "hcomment": "天蓬元帅"
            }
        ],
        "btitle": "西游记",
        "bpub_date": "2020-08-11",
        "bread": 666,
        "bcomment": 123,
        "is_delete": false
    },
    {
        "id": 2,
        "heroinfo_set": [],
        "btitle": "水浒传",
        "bpub_date": "2020-08-11",
        "bread": 200,
        "bcomment": 100,
        "is_delete": false
    },
    {
        "id": 3,
        "heroinfo_set": [],
        "btitle": "红楼梦",
        "bpub_date": "2020-08-11",
        "bread": 0,
        "bcomment": 0,
        "is_delete": false
    },
    {
        "id": 4,
        "heroinfo_set": [],
        "btitle": "三国演义2",
        "bpub_date": "2018-08-19",
        "bread": 0,
        "bcomment": 0,
        "is_delete": false
    }
]

03.多对多序列化

 

# -*- coding: utf-8 -*-
from rest_framework import serializers
from course.models import *


class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = '__all__'  # 所有字段


class SectionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sections
        fields = '__all__'


class ChaptersSerializer(serializers.ModelSerializer):
    sections = SectionsSerializer(many=True)

    class Meta:
        model = Chapters
        fields = '__all__'


class CourseDeepSerializer(CourseSerializer):
    # 字段名名, 必须是模型可以 . 引用到的变量
    # Course().   "chapters"  才能作为字段名,  如果是集合, 需要加many=True,
    chapters = ChaptersSerializer(many=True)
原文地址:https://www.cnblogs.com/xiaoxiamiaichiyu/p/14789361.html