django orm加入三张桌子

时间:2016-08-03 17:59:55

标签: python sql django join

我有三个模型(A,B,C),我需要像这样加入它们:

模型A fk1到模型B pk1然后模型B fk1到模型C.

它正在连接表但没有正确连接它们。我可以将模型a加到b但是它不会让我在第一次加入后从最后一个表(c)中拉出字段。

有效的示例SQL:

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'

Django代码:

TableA.objects.select_related('field1').filter(field2=var).prefetch_related('char1').values('field1', 'field2', 'char1', 'char1__var1', 'char1__var2')

Django models.py:

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' 

1 个答案:

答案 0 :(得分:0)

更新:编辑了问题,因此此答案不再适用。

TableA.objects.filter(field2=var, b__isnull=False, b__c__isnull=True).values(
    'field1', 'field2', 'b__char1', 'b__c__var1', 'b__c__var2',
)
  1. b__isnull=False适用于INNER JOIN tablebb__c__isnull=True适用于LEFT JOIN tablec
  2. 您可以参考values()中相关模型的字段。