title: django orm join three tables
body: <p>I have three models (A, B, C) and I need to join them like so:</p>
  
  <p>Model A fk1 to Model B pk1 and then Model B fk1 to Model C.</p>
  
  <p>It is joining tables but not joining them correctly. I can join model a to b but it won't let me pull fields from the last table (c) after the first join.</p>
  
  <p>Sample SQL that works:</p>
  
  <pre><code>select a.field1, a.field2, b.char1, b.char2, c.var1, c.var2
  from TableA a
  inner join TableB b
      on a.field1 = b.char1
  left join TableC c
      on b.char2 = c.var1
  where a.field2 = 'number'
  </code></pre>
  
  <p>Django code:</p>
  
  <pre><code>TableA.objects.select_related('field1').filter(field2=var).prefetch_related('char1').values('field1', 'field2', 'char1', 'char1__var1', 'char1__var2')
  </code></pre>
  
  <p>Django models.py:</p>
  
  <pre><code>class TableA(models.Model):
  field2 = models.CharField(db_column='FIELD2', max_length=8, primary_key=True) # Field name made lowercase.
  field1 = models.ForeignKey('TableB', db_column='FIELD1', max_length=6) # Field name made lowercase.
  
  class Meta:
      managed = False
      db_table = 'TableA'
  
  class TableB(models.Model):
  
  char1 = models.CharField(db_column='CHAR1', max_length=6) # Field name made lowercase.
  char2 = models.ForeignKey('TableC', db_column='CHAR2', max_length=6, primary_key=True) # Field name made lowercase.
  
  class Meta:
      managed = False
      db_table = 'TableB' 
  
  class TableC(models.Model):
  
  var1 = models.CharField(db_column='VAR1', max_length=6, primary_key=True) # Field name made lowercase.
  var2 = models.CharField(db_column='VAR2', max_length=50) # Field name made lowercase.
  
  class Meta:
      managed = False
      db_table = 'TableC' 
  </code></pre>