title: Querying multiple tables in Django
body: <p>I'm beginner in Django and Python, I started developing survey app. It's based on <a href="https://github.com/jessykate/django-survey" rel="nofollow">https://github.com/jessykate/django-survey</a>
  I added few features, but I'm having problem with results page, to be more precisely how to
  get data to present them. Here's what models with most important fields look like:</p>
  
  <pre><code>class Survey(models.Model):
      name = models.CharField(max_length=250)
  
  class Question(models.Model):
      text = models.TextField()
      survey = models.ForeignKey(Survey)
      choices = models.TextField()
  
  class Response(models.Model):
      survey = models.ForeignKey(Survey)
  
  class AnswerBase(models.Model):
      question = models.ForeignKey(Question)
      response = models.ForeignKey(Response)  
  
  class AnswerText(AnswerBase):
      body = models.TextField(blank=True, null=True)
  
  class AnswerRadio(AnswerBase):
      body = models.TextField(blank=True, null=True)
  
      and few more Answer.. 
  </code></pre>
  
  <p>I think data in this format would be good to process later in js and display as bar char:</p>
  
  <pre><code>results = [{'some_question_text':
              [{'answer':'answer1','count': 11},{'answer':'answer2','count': 6}, ..]}
            ,..]
  </code></pre>
  
  <p>I could't came up how to do it in django way, so i tried in sql. Problem is, it works only with one answer type, when I add another condition like 'or ab.id==polls_answerselect.answerbase_ptr_id' query returns strange results.</p>
  
  <p>Here's what I've done:</p>
  
  <pre><code>cursor = connection.cursor()
  cursor.execute("select q.text as qtext, ar.body as ans, ab.id as Aid, q.id as Qid, count(ar.body) as count \
              from polls_answerbase ab, polls_answerradio ar, polls_question q, polls_survey s \
              where ab.id==ar.answerbase_ptr_id \
              and ab.question_id==q.id \
              and s.id==q.survey_id \
              group by ar.body")
  rows = dictfetchall(cursor)
  result = {}
  for r in rows: 
      res[r['qtext']] = []
      res[r['qtext']].append({'ans': r['ans'], 'count': r['count']})
  </code></pre>
  
  <p>What is better and correct way to solve my problem?</p>