- 创建一个DjangoRestframework应用App, 项目结构如下:
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')
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__'
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)
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
- 效果如下: