title: Recursively querying a many-to-many relationship
body: <p>I'm trying to build a family tree in Django and I can't figure out how to reference an object's children, and the children's children of the object's children, and so on. .</p>
  
  <p>This is my model with the function I'm using to try to get the family tree:</p>
  
  <pre><code>class Member(models.Model):
      referrals = models.ManyToManyField("self", symmetrical=False)
  
      def tree(self):
          refs = {}
          for ref in self.referrals.all():
              refs[ref] = ref.tree()
  
          return refs
  </code></pre>
  
  <p>This seems to work, however, if the children also has children, then it says the following: </p>
  
  <pre><code>maximum recursion depth exceeded while calling a Python object
  </code></pre>
  
  <p>Ideally, I want the tree function to return a string object that is a nested list, so I can just place the result in the template, as follows:</p>
  
  <pre><code>&lt;ul&gt;
      &lt;li&gt;Member A&lt;/li&gt;
      &lt;li&gt;Member B
          &lt;ul&gt;
              &lt;li&gt;Member BA&lt;/li&gt;
               &lt;li&gt;Member BB&lt;/li&gt;
          &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt;Member C&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>Would appreciate any suggestions, thanks</p>