tags:

views:

47

answers:

2

I have these models:

class A(Model): pass

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

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

I have an instance of A called mya.

I want to find all B's for my A, for which there is at least one C. I can do this in one line:

bsiwant = [c.b for c in C.objects.filter(b__a==mya)] (and uniquify it somehow)

...but presumably that would cause many queries. Is there a way to do it with the filter such that a single query would be performed?

+1  A: 

Actually, this should do it:

B.objects.filter(a=mya, c__b__isnull=False)

or

B.objects.filter(a=mya, c__b=F('id'))
Felix Kling
+1  A: 
vals = C.objects.filter(b__a=mya).select_related("b").distinct()
bsiwant = [c.b for c in vals]

Should do it in a single query.

Alex Gaynor