title: Django ORM: Selecting related set
body: <p>Say I have 2 models:</p>
  
  <pre><code>class Poll(models.Model):
      category = models.CharField(u"Category", max_length = 64)
      [...]
  
  class Choice(models.Model):
      poll = models.ForeignKey(Poll)
      [...]
  </code></pre>
  
  <p>Given a Poll object, I can query its choices with:</p>
  
  <pre><code>poll.choice_set.all()
  </code></pre>
  
  <p>But, is there a utility function to query all choices from a set of Poll?</p>
  
  <p>Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be):</p>
  
  <pre><code>polls = Poll.objects.filter(category = 'foo').select_related('choice_set')
  for poll in polls:
      print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration
  </code></pre>
  
  <p>I made an (ugly) function to help me achieve that:</p>
  
  <pre><code>def qbind(objects, target_name, model, field_name):
      objects = list(objects)
      objects_dict = dict([(object.id, object) for object in objects])
      for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}):
          id = getattr(foreign, field_name + '_id')
          if id in objects_dict:
              object = objects_dict[id]
              if hasattr(object, target_name):
                  getattr(object, target_name).append(foreign)
              else:
                  setattr(object, target_name, [foreign])
      return objects
  </code></pre>
  
  <p>which is used as follow:</p>
  
  <pre><code>polls = Poll.objects.filter(category = 'foo')
  polls = qbind(polls, 'choices', Choice, 'poll')
  # Now, each object in polls have a 'choices' member with the list of choices.
  # This was achieved with 2 SQL queries only.
  </code></pre>
  
  <p>Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way.</p>
  
  <p>How do you handle this problem usually?</p>