title: Django querying a nested list of times Django 1.2
body: <p>I have a list of objects which form a tree structure through foreign key relationships.</p>
  
  <pre><code>parent = models.ForeignKey( 'Category', related_name = 'child_set', null = True )
  </code></pre>
  
  <p>So each category object has children which are also category objects. I want to pull them out of the DB in such a way as to hit the database as few times as possible. My former code looked like this:</p>
  
  <pre><code>def get_nested_categories(self):
      categories = []
      for child in self.child_set.all():
           categories.append(child)
           categories += child.get_nested_categories()
      return categories
  </code></pre>
  
  <p>But this causes a many hits to the database and causes slowness, especially as my category list has grown beyond what I expected it to be. Is there a way to optimize this code?</p>