Nested Serializer With ReadOnlyField | Django Rest Framework
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.
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.
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.
Now include this urls in our main school “urls.py” file
After doing the migrations and migrate, lets add some data to our database for testing.
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
Same goes for the teacher “127.0.0.1:8000/teacher”
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.
Download the complete project source code from the github link below.