How to show nested serializer data in parent table(Serializer) single list in python django rest framework

Country table that is grandparent table

class Country(models.Model):
   country_id = models.IntegerField(primary_key=True)
   cname = models.CharField(max_length=100)
   
   def __str__(self):
     return self.name

State table which is a direct child of the country

class State(models.Model):
   stateid = models.IntegerField(primary_key=True)
   state_name= models.CharField(max_length=100)
   s_country = models.ForeignKey(Country, related_name='scountry', on_delete =models.CASCADE)
   
   def __str__(self):
     return self.state_name

City table which is a direct child of State and indirect child of Country

class City(models.Model):
   cityid= models.IntegerField(primary_key=True)
   city_name = models.CharField(max_length=100)
   city_strength = models.IntegerField()
   city_state = models.ForeignKey(State, related_name='cstate', on_delete =models.CASCADE)
   
   def __str__(self):
     return self.sname

Serializers

class StateSerializer(serialiizer.ModelSerializer):
   
   class Meta:
      model = State
      fields = '__all__'


class CitySerializer(serialiizer.ModelSerializer):
   
   class Meta:
      model = City
      fields = '__all__'


class FliterStateCitySerializer(serializers.ModelSerializer):
   state = StateSerializer(many=true)
   cities = CitySerializer(many=true)
   
   class Meta:
      model = Country
      fields = ('id', 'state', 'city')

Views

class FilterStateCityView(generics.ListAPIView):
   queryset = Country.objects.all()
   serializer_class = FliterStateCitySerializer

The response I am getting is.

[
 {
  "country_id":"23",
  "cname": "USA",
  "state" : {
              "stateid": "16",
              "state_name": "Florida",
              "cities" : {
                           "cityid":"55",
                           "city_name": "Miami",
                           "city_strength ": 40005
                         },
                         {
                           "cityid":"56",
                           "city_name": "Orlando",
                           "city_strength ": 930067
                         },

            },
            {
              "stateid": "17",
              "state_name": "Texas",
              "s_country" : "USA"
            },
            
 }
]

Response that i want...

[
 {
  "country_id":"23",
  "stateid": "16",
  "cityid":"55",
  "state_name": "Florida",
  "city_name": "Miami",
  "city_strength ": 40005
 },
 {
  "country_id":"23",
  "stateid": "16",
  "cityid":"56",
  "state_name": "Florida",
  "city_name": "Orlando",
  "city_strength ": 930067
 },
 {
   "stateid": "17",
   "state_name": "Texas",
   "s_country" : "USA"
  },
]

My question is I want to get all states on the basis of country id along with relevant cities in single list as a one-by-one object.

You can use StringRelatedField and PriamryKeyRealtedField to achieve what you are trying to do. You can use source attributes to define the data you want. for e.g.

city_name = serializers.StringRealtedField(source='self.scountry.cstate.city_name')

state_id = serializers.PrimaryKeyRealtedField(source="self.scountry.stateid").

I hope this helps and solves your problem.

Back to Top