DjangoRestFramework实现序列化器的字段嵌套和relate_name应用

  1. 创建一个DjangoRestframework应用App, 项目结构如下:

screenshot_1.png

  1. models.py设计
from django.db import models


class Grade(models.Model):
    name = models.CharField(max_length=32)


class Student(models.Model):
    name = models.CharField(max_length=32)
    grade = models.ForeignKey(Grade, on_delete=models.CASCADE, related_name='grade_student')
  1. serializers.py设计,这里最重要的是注释部分哦~
# -*-coding:utf-8-*-
from rest_framework import serializers

from App.models import Grade, Student


class GradeSerializerForStudent(serializers.ModelSerializer):
    class Meta:
        model = Grade
        fields = '__all__'


class StudentSerializer(serializers.ModelSerializer):
    # student表中grade为外键
    grade = GradeSerializerForStudent()

    class Meta:
        model = Student
        fields = '__all__'


class StudentSerializerForGrade(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'


class GradeSerializer(serializers.ModelSerializer):
    # grade表中没有外键, 使用related_name, 班级和学生是一对多关系,序列化需要指定many=True
    grade_student = StudentSerializerForGrade(many=True)

    class Meta:
        model = Grade
        fields = '__all__'
  1. urls.py设计
# -*-coding:utf-8-*-
from rest_framework.routers import DefaultRouter

from App import views

router = DefaultRouter()
router.register(r'api/grades', views.GradeViewSet)
router.register(r'api/students', views.StudentViewSet)
  1. views.py
# -*-coding:utf-8-*-
from rest_framework.viewsets import ModelViewSet

from App.models import Grade, Student
from App.serializers import GradeSerializer, StudentSerializer


class GradeViewSet(ModelViewSet):
    queryset = Grade.objects.all()
    serializer_class = GradeSerializer


class StudentViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
  1. 效果如下:

screenshot.png
screenshot_3.png

posted @ 2020-05-05 19:53  iread9527  阅读(420)  评论(0编辑  收藏  举报