Django模型INNER JOIN问题

时间:2011-09-09 18:20:15

标签: python django django-models

如何无条件地在两个表之间进行内部连接? 有模型A,B:

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(A)

当我有条件时,我可以写:

A.objects.filter(b__pk=1)

但是如何生成以下查询:

SELECT * from A INNER JOIN B ON a.b = b.pk

1 个答案:

答案 0 :(得分:-1)

for a in A.objects.all():
    for b in a.b_set.all():
        # you have the joined pair a and b

或者

for b in B.objects.all():
    for a in b.a.all():
        # you have the joined pair a and b