前言
一、Serializers嵌套使用
from rest_framework import serializers
from school.models import Student, Course, Teacher, Achievement
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = '__all__'
class CourseSerializer(serializers.ModelSerializer):
teacher = TeacherSerializer()
class Meta:
model = Course
fields = '__all__'
class AchievementSerializer(serializers.ModelSerializer):
course_name = serializers.CharField(source='course.name')
teacher_name = serializers.CharField(source='course.teacher')
class Meta:
model = Achievement
fields = ['score', 'course_name', 'teacher_name']
class AchievementSerializer2(serializers.ModelSerializer):
class Meta:
model = Achievement
fields = '__all__'
depth = 2
class StudentSerializer1(serializers.ModelSerializer):
s_achievment = AchievementSerializer(many=True)
class Meta:
model = Student
fields = ['id', 'name', 'sex', 'age', 's_achievment']
class StudentSerializer2(serializers.ModelSerializer):
s_achievment = AchievementSerializer2(many=True)
class Meta:
model = Student
fields = ['id', 'name', 'sex', 'age', 's_achievment']
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['id', 'name', 'sex', 'age', 'achievement']
from django.db import models
from django.utils import timezone as datetime
class Student(models.Model):
name = models.CharField(max_length=50, verbose_name="姓名")
age = models.SmallIntegerField(verbose_name="年龄")
sex = models.BooleanField(default=False)
class Meta:
db_table = "sch_student"
def __str__(self):
return self.name
@property
def achievement(self):
""" 成绩表 """
return self.s_achievment.values('course__name', 'course__teacher__name', 'score')
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.BooleanField(default=False)
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_achievment", 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"
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from school.models import Student,
from school.serializers import StudentSerializer
class StudentModelViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer