django由链式外键过滤

时间:2014-09-17 15:22:02

标签: django

假设有如下代码:

class A(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

class B(models.Model):
    name = models.CharField(max_length=100)
    a = models.ForeignKey(A)

    def __unicode__(self):
        return self.name

class C(models.Model):
    name = models.CharField(max_length=100)
    b = models.ForeignKey(B)

    def __unicode__(self):
        return self.name


class X(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Y(models.Model):
    name = models.CharField(max_length=100)
    x = models.ForeignKey(X)
    c = models.ForeignKey(C)

    def __unicode__(self):
        return "%s(%s-%s)" % (self.name, self.x.name, self.c.name)

我想过滤A以获得所有'A',其中'C'属于A链接的X实例(通过Y)。这是一个例子:

a1 = A.objects.create(name='A1')
a2 = A.objects.create(name='A2')

b11 = B.objects.create(name='B11', a=a1)
b12 = B.objects.create(name='B12', a=a1)

c111 = C.objects.create(name='C111', b=b11)
c112 = C.objects.create(name='C112', b=b11)
c113 = C.objects.create(name='C113', b=b11)

x1 = X.objects.create(name='X1')

y1 = Y.objects.create(name='Y1', x=x1, c=c111)

我想在A上过滤以获得连接'x1'的实例列表(通过Y - > C - > B - > A),在此示例中预期结果为[a1]。

如果我继续添加:

b21 = B.objects.create(name='B21', a=a2)
c211 = C.objects.create(name='C211', b=b21)
y2 = Y.objects.create(name='Y2', x=x1, c=c211)

预期结果是[a1,a2]。

有没有简单的方法可以做到这一点?

对不起,我觉得用英语解释一下有点难:(

1 个答案:

答案 0 :(得分:0)

试试这个。假设x1是类x的实例,

 a_results = A.objects.filter(b__c__y__x=x1) #or x__name if x1 is a string

文档reverse lookups, and lookups that span relations