Reputation: 258
Please excuse me for this silly question, I'm a beginner and I can't find my way through documents.
I have two models:
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)
I want to have a list of students which includes all data of school in it:
[
{
"name": "John",
"family": "Doe"
"school": {
"name": "J.F.K",
"rate": 1
}
}
...
]
How can I do this with django ORM
?
Upvotes: 1
Views: 231
Reputation: 585
You can easily adapt the Django Rest Framework's documentation on nested relationships for your needs:
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)
Upvotes: 3
Reputation: 599550
This question has nothing to do with the Django orm and everything to do with DRF serialisers, which are well documented.
See serialiser relations for a full description, in particular the section on nested serialisers halfway down.
Upvotes: 4