title: How to fetch Django models objects/queryset as dictionary in case of multiple levels of relationship?
body: <p>I have 3 models:</p>
  
  <pre><code>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()
  
  </code></pre>
  
  <p>Now given a <code>country_id</code>, I want to fetch all the related <code>State</code> and <code>District</code>  in following format:</p>
  
  <pre><code>{
      '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
                  }]
              },
              {
                  &lt;2nd state data here&gt;
              }
          ]
      }
  }
  
  </code></pre>
  
  <p>Also I should be able select particular columns from each of the model.</p>
  
  <blockquote>
    <p>For Eg: Only <code>state_name</code> from <code>State</code> Model, <code>district_name</code> and <code>district_population</code> from <code>District</code> Model, etc</p>
  </blockquote>
  
  <p>I also need the feature of filtering, at different models. </p>
  
  <blockquote>
    <p>For eg: Only get districts matching condition district.population >
    5000</p>
  </blockquote>
  
  <p>None of the question I could find here helped to solve the problem. Closest one seemed to be this :
  <a href="https://stackoverflow.com/questions/37626867/django-most-efficient-way-to-create-a-nested-dictionary-from-querying-related-m">Django: Most efficient way to create a nested dictionary from querying related models?</a></p>
  
  <p>But here the relationship is in opposite direction.</p>
  
  <p>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.</p>