Nested Serializer With ReadOnlyField | Django Rest Framework

binary-ibex
3 min readFeb 21, 2021

--

Simple example of the nested serializer in the django. Let’s start with our project structure. It consist of school and classroom with bunch of teachers and students, that’s it.

Project structure

Let’s create the model for the teacher and students.

Make new file called “serializer.py” inside the classroom app and write the serializer. Before writing serializer remember what we want. We want the list of students with there respective teachers and when we list the teacher we also want to students under them.

student teacher serializer

Now let’s create a sweet little view for the our project in “views.py” file

Now to access our view create the “urls.py” file inside the classroom app and put some urls.

urls file for the view

Now include this urls in our main school “urls.py” file

main app url file

After doing the migrations and migrate, lets add some data to our database for testing.

data in the teacher table
data inside the student table

Now runserver and test api in the browser

As expected, api “127.0.0.1:8000/student” show us bunch of students with there respective teacher. We can also request for specific student only, by providing the id in url

request student with id 1 (127.0.0.1:8000/student/1)

Same goes for the teacher “127.0.0.1:8000/teacher”

all teacher with student api output

Observer in above image, “Epictetus” has two students while other two has only one student each. We can also get the detail of the specific teacher only by id.

teacher with id 1 detail

Download the complete project source code from the github link below.

--

--

binary-ibex
binary-ibex

Written by binary-ibex

0 Followers

Simple and Easy

No responses yet