Nested Relationships in Serializers for OneToOne fields in Django Rest Framework
The Django Rest Framework (DRF) is one of the effectively written frameworks around Django and helps build REST APIs for an application back-end.
I was using it in one of my personal projects and stumbled upon this challenge of “serializing a model which is referencing another model via OneToOne field.”
`I was using the User model from
django.contrib.auth.models. I wanted to write an API to create and update a user object through a single API which also updates my model’s attributes. The solution was to use DRF’s Nested Relationships in serialization.
I shall assume you have a fair working knowledge of Python, virtualenv, pip, Django and DRF before proceeding. If not, please learn more and feel free to return if you are ever stuck on nested relationships in serialization.
The example I am considering here is a University Student model, referencing User model via the OneToOne field. My goal is a single API for creating and getting user details like name, username, and email along with a student attribute such as subject major.
Here is how my
Next, the serializer for the above model determines the attributes to manipulate. If you observe below, I have 2 serializer classes,
StudentSerializer. This is our point of interest.
I have declared a
user attribute which is a serializer field here. That
user attribute will primarily hold the entire reference for the
UserSerializer class. In the fields of
StudentSerializer , we just see ‘
user’ and ‘
subject_major’. This allows us to enter the student (or user) attributes along with the subject_major.
A user entry is created which is referenced by the student entry. We override the create method of
StudentSerializer to create a
user object first, and use that to create the
serializer.py is as follows:
views.py should be quite straightforward if you are already familiar with the class-based views of Django. We will be using the serializer to validate and create the model objects:
I have included
url for achieving
get requests for university student.
POST request call would look something like this:
Get request call would look something like this:
Nested Relationship is thus enabled on
StudentSerializer to reference
Complete code is in my gitlab repository.