开发者

django - 3-model set all, with joining?

I have these models:

class A(Model): pass

class B(Model): the_a = ForeignKey(A)

class C(Model): the_b = ForeignKey(B)

somewhere in code, I have an A instance. I know how to get all of the B's associated with 开发者_StackOverflow社区A; A.b_set.all() - but is there a way to get all of the C's associated with all the B's associated with my A, without doing potentially many queries?


You can execute this query to get all the C's associated via B's to your A:

C.objects.filter(the_b__the_a=instance_of_a)

where instance_of_a is some instance of class A.

For more information, see http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships


This doesn't directly answer your question, but it's possible in straight SQL with a single query, so it may be possible in Django, but it depends on the way their wrappers over SQL were written.

Example:

SELECT C.* FROM B,C WHERE C.the_b = B.id AND B.the_a = ?

Where ? is the ID of the A you are interested in.


OK, I should have RTM:

my_a = Some instance of A

cs_for_my_a = C.objects.filter(the_b__the_a=my_a)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜