请原谅我这个愚蠢的问题,我是一个初学者,我无法通过文件找到答案。
我有两种模式:
class Student (models.Model):
name = models.CharField(max_length=40)
family = models.CharField(max_length=40)
school = models.ForeignKey(School)
class School (models.Model):
name = models.CharField(max_length=40)
rate = models.IntegerField(default=-1)
我想要一份学生名单,其中包括所有学校的数据:
[
{
"name": "John",
"family": "Doe"
"school": {
"name": "J.F.K",
"rate": 1
}
}
...
]
如何使用django ORM
?
答案 0 :(得分:4)
这个问题与Django orm无关,而且与DRF序列化器有关,这些都是有据可查的。
有关完整说明,请参阅serialiser relations,特别是有关嵌套序列化程序中途的部分。
答案 1 :(得分:3)
您可以根据需要轻松调整Django Rest Framework的documentation on nested relationships:
from rest_framework import serializers
from my_models import School, Student
class SchoolSerializer(serializers.ModelSerializer):
class Meta:
model = School
fields = ('name', 'rate')
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('name', 'family', 'school')
school = SchoolSerializer(read_only=True)