views:

101

answers:

3

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 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?

A: 

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.

davr
+1  A: 

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

Clueless
A: 

OK, I should have RTFM:

my_a = Some instance of A

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

Colin