Reputation: 304
I have two simple models, and serializers for Course
and Department
as below: (A course belongs to a department, that is many to one relationship from Course
to Department
)
# models.py
# Department Model
class Department(models.Model):
name = models.CharField(max_length=256)
location = models.CharField(max_length=1024)
# Course Model
class Course(models.Model):
code = models.CharField(max_length=15, unique=True)
name = models.CharField(max_length=15, unique=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE, default=None,
null=True, blank=True)
###################################
# serializers.py
# Department serializer
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Department
fields = ['id', 'name']
# Course serializer
class CourseSerializer(serializers.ModelSerializer):
department = DepartmentSerializer()
class Meta:
model = Course
fields = '__all__'
After adding some courses through SQL Queries, I made a GET
request to the end point localhost:8000/courses/
which gives the expected result.
[
{
"id": 1,
"code": "SS240",
"name": "Sociology",
"department": {
"id": 1,
"name": "Humanities"
}
},
{
"id": 2,
"code": "CS310",
"name": "Data Structures and Algorithms",
"department": {
"id": 5,
"name": "Computer Sciences"
}
}
]
I want to make a POST
request to the end point localhost:8000/courses/
. Say, I have a department with name = Computer Sciences with id = 5. I want to add a course with code=CS330, name = Object Oriented Design, department = Computer Sciences. How should I write the body of the request?
The following gives the error because of nested representation of department
{
"code": "CS330",
"name": "Object Oriented Design",
"department": 5
}
Should it be like this?
{
"code": "CS330",
"name": "Object Oriented Design",
"department": {
"id": 5,
"name": "Computer Sciences"
}
}
How should I overrride the .create()
method?
Upvotes: 1
Views: 318
Reputation: 88449
Override your to_representation(...)
method of CourseSerializer
class
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = '__all__'
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['department'] = DepartmentSerializer(instance.department).data
return rep
Reference:
Upvotes: 1