title: django orm - How to use select_related() on the Foreign Key of a Subclass from its Super Class
body: <p>I've always found the Django orm's handling of subclassing models to be pretty spiffy. That's probably why I run into problems like this one.</p>
  
  <p>Take three models:</p>
  
  <pre><code>class A(models.Model):
      field1 = models.CharField(max_length=255)
  
  class B(A):
      fk_field = models.ForeignKey('C')
  
  class C(models.Model):
      field2 = models.CharField(max_length=255)
  </code></pre>
  
  <p>So now you can query the <code>A</code> model and get all the <code>B</code> models, where available:</p>
  
  <pre><code>the_as = A.objects.all()
  for a in the_as:
      print a.b.fk_field.field2 #Note that this throws an error if there is no B record
  </code></pre>
  
  <p>The problem with this is that you are looking at a huge number of database calls to retrieve all of the data.</p>
  
  <p>Now suppose you wanted to retrieve a QuerySet of all <code>A</code> models in the database, but with all of the subclass records and the subclass's foreign key records as well, using <code>select_related()</code> to limit your app to a single database call. You would write a query like this:</p>
  
  <pre><code>the_as = A.objects.select_related("b", "b__fk_field").all()
  </code></pre>
  
  <p>One query returns all of the data needed! Awesome.</p>
  
  <p>Except not. Because this version of the query is doing its own filtering, even though <code>select_related</code> is not supposed to filter any results at all:</p>
  
  <pre><code>set_1 = A.objects.select_related("b", "b__fk_field").all() #Only returns A objects with associated B objects
  set_2 = A.objects.all() #Returns all A objects
  len(set_1) &gt; len(set_2) #Will always be False
  </code></pre>
  
  <p>I used the django-debug-toolbar to inspect the query and found the problem. The generated SQL query uses an <code>INNER JOIN</code> to join the <code>C</code> table to the query, instead of a <code>LEFT OUTER JOIN</code> like other subclassed fields:</p>
  
  <pre><code>SELECT "app_a"."field1", "app_b"."fk_field_id", "app_c"."field2"
  FROM "app_a" 
      LEFT OUTER JOIN "app_b" ON ("app_a"."id" = "app_b"."a_ptr_id") 
      INNER JOIN "app_c" ON ("app_b"."fk_field_id" = "app_c"."id");
  </code></pre>
  
  <p>And it seems if I simply change the <code>INNER JOIN</code> to <code>LEFT OUTER JOIN</code>, then I get the records that I want, but that doesn't help me when using Django's ORM.</p>
  
  <p>Is this a bug in <code>select_related()</code> in Django's ORM? Is there any work around for this, or am I simply going to have to do a direct query of the database and map the results myself? Should I be using something like Django-Polymorphic to do this? </p>