Skip to content
Advertisement

how to return nested json using django rest framework

I am trying build a REST API using django. here is my models.py and serializers.py.

models.py

from django.db import models

class Person(models.Model):

    city = models.CharField(max_length=100)
    dob = models.DateField(editable=True)
    personName = models.CharField(max_length=100)

    class Meta:
        ordering = ['-dob']

serailizers.py

from rest_framework import serializers
from .models import Person

class PersonSerializer(serializers.ModelSerializer):
 
    class Meta:
        model = Person
        fields = [ 'id', 'city', 'dob', 'personName']

Here is my api – http://127.0.0.1:8000/api/city/Sidney/. I am trying to fetch data by city name.

I am getting the json in below format.

[{
  "id": 1,
  "city": "Sidney",
  "personName": "Giles",
  "dob": "2011-02-02"
},
{
  "id": 5,
  "city": "Paulba",
  "personName": "Sidney",
  "dob": "2016-07-16"
}]

But i want the json in below shown format –

[
  {
    "id": 123,
    "city": "Sidney",
    "personInCity": [
      {
        "id": 1,
        "city": "Sidney",
        "personName": "Giles",
        "dob": "2011-02-02"
      },
      {
        "id": 5,
        "city": "Paulba",
        "personName": "Sidney",
        "dob": "2016-07-16"
      }
    ]
  }
]

i am not getting what change needs to be done in Serializers.py

Advertisement

Answer

To get correct response you might need to change your models.py and Serializers.py as below

#----------models.py-----------
from django.db import models


class City(models.Model):
    city = models.CharField(max_length=100)

    def __str__(self):
      return self.city


class Person(models.Model):
    dob = models.DateField(editable=True)
    personName = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True, 
           related_name="personInCity")

    class Meta:
      ordering = ['-dob']

    def __str__(self):
       return self.personName

#----------Serializers.py-----------
from rest_framework import serializers
from .models import Person, City


class PersonSerializer(serializers.ModelSerializer):
    city = serializers.StringRelatedField(many=False)

    class Meta:
      model = Person
      fields = ("id", "personName", "dob", "city",)


class CitySerializer(serializers.ModelSerializer):
    personInCity=PersonSerializer(many=True)

    class Meta:
      model = City
      fields = ("id", "city","personInCity")

Should give you the response like this:

Screenshot of API response, as per your question

Advertisement