不做大哥好多年 不做大哥好多年
首页
  • MySQL
  • Redis
  • Elasticsearch
  • Kafka
  • Etcd
  • MongoDB
  • TiDB
  • RabbitMQ
  • 01.Python
  • 02.GO
  • 03.Java
  • 04.业务问题
  • 05.关键技术
  • 06.项目常识
  • 10.计算机基础
  • Docker
  • K8S
  • 容器原理
  • Istio
  • 01.GO基础
  • 02.面向对象
  • 03.并发编程
  • 04.常用库
  • 05.数据库操作
  • 06.Beego框架
  • 07.Beego商城
  • 08.GIN框架
  • 09.GIN论坛
  • 10.微服务
  • 01.Python基础
  • 02.Python模块
  • 03.Django
  • 04.Flask
  • 05.SYL
  • 06.Celery
  • 10.微服务
  • 01.Java基础
  • 02.面向对象
  • 03.Java进阶
  • 04.Web基础
  • 05.Spring框架
  • 100.微服务
  • 数据结构
  • 算法基础
  • 算法题分类
  • 前置知识
  • PyTorch
  • Langchain
  • Linux基础
  • Linux高级
  • Nginx
  • KeepAlive
  • ansible
  • zabbix
  • Shell
  • Linux内核

逍遥子

不做大哥好多年
首页
  • MySQL
  • Redis
  • Elasticsearch
  • Kafka
  • Etcd
  • MongoDB
  • TiDB
  • RabbitMQ
  • 01.Python
  • 02.GO
  • 03.Java
  • 04.业务问题
  • 05.关键技术
  • 06.项目常识
  • 10.计算机基础
  • Docker
  • K8S
  • 容器原理
  • Istio
  • 01.GO基础
  • 02.面向对象
  • 03.并发编程
  • 04.常用库
  • 05.数据库操作
  • 06.Beego框架
  • 07.Beego商城
  • 08.GIN框架
  • 09.GIN论坛
  • 10.微服务
  • 01.Python基础
  • 02.Python模块
  • 03.Django
  • 04.Flask
  • 05.SYL
  • 06.Celery
  • 10.微服务
  • 01.Java基础
  • 02.面向对象
  • 03.Java进阶
  • 04.Web基础
  • 05.Spring框架
  • 100.微服务
  • 数据结构
  • 算法基础
  • 算法题分类
  • 前置知识
  • PyTorch
  • Langchain
  • Linux基础
  • Linux高级
  • Nginx
  • KeepAlive
  • ansible
  • zabbix
  • Shell
  • Linux内核
  • python基础

  • python模块

  • django

    • 01_Django基础

    • 02_Model数据库操作

    • 03_DRF框架

      • 01.web开发两种模式
      • 02.Restful风格
      • 03.DRF框架作用
      • 04.环境安装与使用
      • 05.Serializer
      • 06.ModelSerializer
        • 01.ModelSerializer
          • 1.1 ModelSerializer特点
          • 1.2 定义ModelSerializer语法
          • 1.3 查看自动生成字段
        • 02.ModelSerializer使用
          • 2.1 book/serializers.py
          • 2.2 查询结果
        • 03.多对多序列化
      • 07.APIView
      • 08.初始化项目结构
      • 09.ModelViewSet
    • 04_部署

  • flask

  • SYL

  • Celery

  • 微服务

  • python
  • django
  • 03_DRF框架
xiaonaiqiang
2021-02-17
目录

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
2
3
4
5
6
7
8
9
10
11
12
13

# 1.3 查看自动生成字段

(django2.2) C:\tmp\drf_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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 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__'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 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
    }
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

# 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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
上次更新: 2024/3/13 15:35:10
05.Serializer
07.APIView

← 05.Serializer 07.APIView→

最近更新
01
05.快递Agent智能体
06-04
02
200.AI Agent核心概念
06-04
03
105.Agent智能体梳理
06-04
更多文章>
Theme by Vdoing | Copyright © 2019-2025 逍遥子 技术博客 京ICP备2021005373号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式