title: expanding the SQL query inside managers in Django models?
body: <p>Here is the <a href="https://docs.djangoproject.com/en/1.6/topics/db/managers/" rel="nofollow">code</a> from django docs that explains the use of managers. </p>
  
  <pre><code>class PollManager(models.Manager):
      def with_counts(self):
          from django.db import connection
          cursor = connection.cursor()
          cursor.execute("""
              SELECT p.id, p.question, p.poll_date, COUNT(*)
              FROM polls_opinionpoll p, polls_response r
              WHERE p.id = r.poll_id
              GROUP BY p.id, p.question, p.poll_date
              ORDER BY p.poll_date DESC""")
          result_list = []
          for row in cursor.fetchall():
              p = self.model(id=row[0], question=row[1], poll_date=row[2])
              p.num_responses = row[3]
              result_list.append(p)
          return result_list
  
  class OpinionPoll(models.Model):
      question = models.CharField(max_length=200)
      poll_date = models.DateField()
      objects = PollManager()
  
  class Response(models.Model):
      poll = models.ForeignKey(OpinionPoll)
      person_name = models.CharField(max_length=50)
      response = models.TextField()
  </code></pre>
  
  <p>I have two questions based on this code:</p>
  
  <p>1) where is <code>r.poll_id</code> coming from? I understand <em>Response</em> has <code>foreignKey</code> relationship to <em>OpinionPoll</em>. In order to JOIN <em>OpinionPoll</em> table with <em>Response</em> table, I need to join on their id.
  HOwever to access the poll id in <em>Response</em>, I would do r.poll.id. 
  Is the syntax, <code>r.poll_id</code>, a MySQL syntax. </p>
  
  <p>why GROUP BY p.id, p.question, p.poll_date? why  GROUP BY p.id alone is not sufficient?</p>
  
  <p>2) Is it possible to turn the above raw SQL query into a django ORM query?If so how would that look like?</p>
  
  <p>I am not a SQL guy. so bear with me, if this sounds stupid</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>If I want to create OpinionPoll and Response tables outside of Django, how will SQL statment for <code>create</code> look like?</p>
  
  <p>In the Django shell, when I run</p>
  
  <p><code>python manage.py sqlall appname</code></p>
  
  <p>I get the following: </p>
  
  <pre><code>BEGIN;
  
  CREATE TABLE "myapp_opinionpoll" (
      "id" integer NOT NULL PRIMARY KEY,
      "question" varchar(200) NOT NULL,
      "poll_date" date NOT NULL
  )
  ;
  CREATE TABLE "myapp_response" (
      "id" integer NOT NULL PRIMARY KEY,
      "poll_id" integer NOT NULL REFERENCES "myapp_opinionpoll" ("id"),
      "person_name" varchar(50) NOT NULL,
      "response" text NOT NULL
  )
  ;
  CREATE INDEX "larb_response_70f78e6b" ON "myapp_response" ("poll_id");
  
  COMMIT;
  </code></pre>
  
  <p>I see something like <code>REFERENCES "myapp_opinionpoll"</code> and <code>CREATE INDEX</code>above. I am not sure 
  if this is how in SQL it is done?</p>