I have 3 models:
class Country(models.Model):
country_id = models.AutoField(primary_key=True)
country_name = models.CharField(max_length=50)
population = models.BigIntegerField()
class State(models.Model):
state_id = models.AutoField(primary_key=True)
state_name = models.CharField(max_length=50)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
population = models.BigIntegerField()
class District(models.Model):
state_id = models.AutoField(primary_key=True)
district_name = models.CharField(max_length=50)
state = models.ForeignKey(State, on_delete=models.CASCADE)
population = models.BigIntegerField()
Now given a country_id
, I want to fetch all the related State
and District
in following format:
{
'country':{
'country_id': 1,
'coutry_population': 120000,
'state':[
{
'state_id': 10,
'state_name': 'A',
'state_population': 10000,
'district':[
{
'district_id': 100,
'district_name': 'District1',
'district_population': 4000
},
{
'district_id': 101,
'district_name': 'District2',
'district_population': 6000
}]
},
{
<2nd state data here>
}
]
}
}
Also I should be able select particular columns from each of the model.
For Eg: Only
state_name
fromState
Model,district_name
anddistrict_population
fromDistrict
Model, etc
I also need the feature of filtering, at different models.
For eg: Only get districts matching condition district.population > 5000
None of the question I could find here helped to solve the problem. Closest one seemed to be this : Django: Most efficient way to create a nested dictionary from querying related models?
But here the relationship is in opposite direction.
One solution I could think of was to query each of the models differently, and store them in dictionary, and combine later. But if I could get more of a direct approach, that would be helpful.