title: Django: Tree stored in DB, derive JSON
body: <p>I have a model like so:</p>
  
  <pre><code>class Node(models.Model):
      parent = models.ForeignKey(Node, null=True)
  </code></pre>
  
  <p>Let us assume I have the following tree stored using this DB structure: </p>
  
  <p><a href="https://i.stack.imgur.com/xAhfP.png" rel="nofollow noreferrer">Tree Structure</a></p>
  
  <p>What is the most efficient way to obtain a JSON in the following structure, in a query written in Django's ORM?</p>
  
  <pre><code>{"node": "A", "children": [
      {"node": "B2", "children": [
          {"node": "C1", "children": []}, 
          {"node": "C2", "children": []}
      ]}, 
      {"node": "B1", "children": []}
  ]}
  </code></pre>
  
  <p>EDIT: </p>
  
  <p>I do not want to use django-mptt or similar packages. I do not want to use JSON fields either. My question is around how one would write a query for this use case, and what the most efficient query would be.</p>