0

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.