• 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

  • 相关阅读:
    关于字体单位em的问题
    键盘按钮keyCode大全
    右侧导航栏(动态添加数据到list)
    当前页面点击取到值
    前端写分页(用了自己同事写的插件)
    选择控件js插件和使用方法
    Form表单验证
    前端页面跳转并取到值
    App配置页面头部
    json字符串、json对象、数组之间的转换
  • 原文地址:https://www.cnblogs.com/iread9527/p/12832395.html
Copyright © 2020-2023  润新知