This is a bit of a puzzle, I have these pseudo models:
class Country(models.Model):
name = models.CharField(unique=True)
class Region(models.Model):
name = models.CharField(unique=True)
country = models.ForeignKey(Country)
class SubRegion(models.Model):
name = models.CharField(unique=True)
region = models.ForeignKey(Region)
class Estate(models.Model):
name = models.CharField(unique=True)
sub_region = models.ForeignKey(SubRegion)
I am trying to JSON serialize their data as below. However i’m not sure how to do this effectively (avoiding too much database queries), suggestions are appreciated
{
CountryX: {
RegionX {
SubRegionX = [
"EstateX"
"EstateY",
"EstateZ"
],
SubRegionY = [ etc... ]
},
RegionY { etc... }
},
CountryY: { etc... }
}
I haven’t tested this, but it should give you the idea. Start with the innermost object, use select_related to traverse the heirarchy, then loop over the innermost objects, adding the keys for the heirarchy as needed.
Just a note of warning, if there are Countries/Regions/Subregions without any estates, they won’t be included in the JSON. If that’s not OK, you’ll need to query each of the models separately.