Serializers嵌套使用


前言


一、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 = CourseSerializer()
    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__'
        # 指定关联深度
        # 从成绩模型 -> 课程 =1
        # 从成绩模型 -> 课程 ->老师 = 2
        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']


# 第三种序列化嵌套方式,更改models类
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="成绩")
   # db_constraint 虚拟外键
   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"

   # def __str__(self):
   #     return str(self.score)

  • 视图类
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

下面是一个 DRF 实现多级嵌套数据的完整例子,展示了如何使用 Serializer 嵌套来实现多级嵌套数据的 API: models.py: ```python from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name ``` serializers.py: ```python from rest_framework import serializers from .models import Category, Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'price') class CategorySerializer(serializers.ModelSerializer): products = ProductSerializer(many=True) class Meta: model = Category fields = ('id', 'name', 'products') ``` views.py: ```python from rest_framework import viewsets from .models import Category, Product from .serializers import CategorySerializer, ProductSerializer class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer ``` 在上面的例子中,Category 表示类别模型,其中包含了类别的名称,Product 表示产品模型,其中包含了产品的名称、价格和所属类别。在 ProductSerializer 中,表示产品的序列化器,只包含了产品的基本信息。在 CategorySerializer 中,表示类别的序列化器,通过 ProductSerializer嵌套表示产品的信息。在 CategoryViewSet 和 ProductViewSet 中,分别表示类别和产品的 API 视图集合,其中 CategoryViewSet 中的 queryset 包含了所有的类别,ProductViewSet 中的 queryset 包含了所有的产品。通过访问 /categories/ 可以获取所有的类别信息,包含了每个类别的所有产品信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值