title: Django - queries made repeat/inefficient
body: <p>Alright, I have a Django view, like this:</p>
  
  <pre><code>@render_to('home/main.html')
  def login(request):
      # also tried Client.objects.select_related().all()
      clients = Client.objects.all()
      return {'clients':clients}
  </code></pre>
  
  <p>And I have a template, <code>main.html</code>, like this:</p>
  
  <pre><code>&lt;ul&gt;
  {% for client in clients %}
  &lt;li&gt;{{ client.full_name }}&lt;/li&gt;
      &lt;ul&gt;
      {% for pet in client.pets.all %}
          &lt;li&gt;{{ pet.full_name }}&lt;/li&gt;
      {% endfor %}
      &lt;/ul&gt;
  {% endfor %}
  &lt;/ul&gt;
  </code></pre>
  
  <p>I also print out all the queries in <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-debug" rel="nofollow noreferrer"><code>sql_queries</code></a> at the bottom of my base template. When I run this view, the following queries are made:</p>
  
  <pre><code>SELECT `home_client`.`id`, ... FROM `home_client`;
  SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 1;
  SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
  SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 1;
  SELECT `home_pet`.`id`, ... FROM `home_pet` WHERE `home_pet`.`client_id` = 2;
  SELECT `home_client`.`id`, ... FROM `home_client` WHERE `home_client`.`id` = 2; 
  </code></pre>
  
  <p>My question is, why are all these queries being made? Shouldn't it just be 1 query to retrieve all the clients and a query per client to retrieve all the pets from each client? I have 2 clients in the <code>home_client</code> table, so it should be 3 queries total. Most troubling of all is that queries 3 and 4 are 100% identical. I don't want to "prematurely optimize" or anything but I do want to make sure Django isn't being wildly inefficient. Any help on this would be appreciated. Thanks.</p>