序列化器的嵌套
(1) 新建一个应用
python manage.py startapp school
(2) 注册应用
INSTALLED_APPS = [
# 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'app', # django原生接口
'app01', # drf接口
'sers', # 序列化器的使用
'req', # drf提供的请求与响应
'viewdemo', # 视图
'school', # 序列化器的嵌套
'rest_framework',
]
(3) 新建数据模型
from datetime import datetime
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=50, verbose_name="姓名")
age = models.SmallIntegerField(verbose_name="年龄")
sex = models.CharField(max_length=1, default="男", verbose_name="性别")
class Meta:
db_table = "sch_student"
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=50, verbose_name="课程名称")
teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, related_name="course", db_constraint=False)
class Meta:
db_table = "sch_course"
def __str__(self):
return self.name
class Teacher(models.Model):
name = models.CharField(max_length=50, verbose_name="姓名")
sex = models.CharField(max_length=1, default="男", verbose_name="性别")
class Meta:
db_table = "sch_teacher"
def __str__(self):
return self.name
class Achievement(models.Model):
score = models.DecimalField(default=0, max_digits=4, decimal_places=1, verbose_name="成绩")
student = models.ForeignKey(Student, on_delete=models.DO_NOTHING, related_name="s_achievement", db_constraint=False)
course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, related_name="c_achievement", db_constraint=False)
create_dtime = models.DateTimeField(auto_created=datetime.now())
class Meta:
db_table = "sch_achievement"
def __str__(self):
return str(self.score)
(4) 数据迁移
python manage.py makemigrations
python manage.py migrate
(5) 创建序列化器
from rest_framework import serializers
from .models import *
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = "__all__"
class CourseSerializer(serializers.ModelSerializer):
teacher = TeacherSerializer()
class Meta:
model = Course
fields = ["id", "name", "teacher"]
class AchievementModelSerializer(serializers.ModelSerializer):
course = CourseSerializer()
class Meta:
model = Achievement
fields = ["id", "score", "course", "create_dtime"]
class StudentSerializer(serializers.ModelSerializer):
# 多条数据的话要加many=True
s_achievement = AchievementModelSerializer(many=True) # s_achievement必须是s_achievement,也就是定义的外键名
class Meta:
model = Student
fields = ["id", "name", "age", "sex", "s_achievement"]
(6) 视图
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
class StudentModelViewset(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
(7) 路由
from django.urls import path
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("students", views.StudentModelViewset, basename="students")
urlpatterns = [
] + router.urls
总路由如下:
from django.urls import path, include
urlpatterns = [
# path('admin/', admin.site.urls),
path('api/',include('app.urls')),
path('api/', include('app01.urls')),
path('sers/', include('sers.urls')),
path('req/', include('req.urls')),
path('viewdemo/', include('viewdemo.urls')),
path('school/', include('school.urls')),
]
(8) 访问效果如下
GET 127.0.0.1:8000/school/students/
[
{
"id": 1,
"name": "小红",
"age": 22,
"sex": "女",
"s_achievement": [
{
"id": 1,
"score": "1.0",
"course": {
"id": 1,
"name": "语文",
"teacher": {
"id": 1,
"name": "张老师",
"sex": "男"
}
},
"create_dtime": null
}
]
},
{
"id": 2,
"name": "小明",
"age": 23,
"sex": "男",
"s_achievement": [
{
"id": 2,
"score": "2.0",
"course": {
"id": 1,
"name": "语文",
"teacher": {
"id": 1,
"name": "张老师",
"sex": "男"
}
},
"create_dtime": null
}
]
},
{
"id": 3,
"name": "小花",
"age": 21,
"sex": "女",
"s_achievement": [
{
"id": 3,
"score": "1.0",
"course": {
"id": 2,
"name": "数学",
"teacher": {
"id": 2,
"name": "李老师",
"sex": "男"
}
},
"create_dtime": null
}
]
},
{
"id": 4,
"name": "张三",
"age": 24,
"sex": "男",
"s_achievement": [
{
"id": 4,
"score": "3.0",
"course": {
"id": 3,
"name": "英语",
"teacher": {
"id": 3,
"name": "王老师",
"sex": "女"
}
},
"create_dtime": null
},
{
"id": 5,
"score": "2.0",
"course": {
"id": 4,
"name": "操作系统",
"teacher": {
"id": 1,
"name": "张老师",
"sex": "男"
}
},
"create_dtime": null
}
]
},
{
"id": 5,
"name": "李四",
"age": 25,
"sex": "男",
"s_achievement": []
},
{
"id": 6,
"name": "王二",
"age": 20,
"sex": "男",
"s_achievement": []
}
]
标签:name,models,sex,id,嵌套,序列化,class,achievement
From: https://www.cnblogs.com/minqiliang/p/16822182.html