Filtering across tables

13 views
Skip to first unread message

Craig

unread,
Dec 8, 2011, 12:36:07 PM12/8/11
to Django users
Hi -

I'm pretty new to Django and I'm trying to do something that's
probably pretty easy, but getting it to happen is eluding me. Here's a
simplified version of what I want to do:

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

class B(models.Model):
info = models.CharField(max_length = 10)
a = models.ForeignKey(A)

class C(models.Model):
stuff = models.CharField(max_length = 10)
b = models.ForeignKey(B)

A is one-to-many to B and B is one-to-many to C.

If I know which A I'm interested in [eg, a_instance = A.objects.get(pk
= 1)], is there a way to get all the instances of C that are related
to a_instance in one step?

I know how to get all the B's related to my a_instance and then I can
loop through those to get all their C instances, but that's really
slow. Reading the docs seems to imply I can do this in one step, but
I'm having issues figuring out how it's actually done.

TIA,
- Craig

Craig Amundsen

unread,
Dec 8, 2011, 1:16:23 PM12/8/11
to Django users
Hi -

Responding to myself...

Doesn't this always happen? As soon as you ask for help, you figure out the solution.

Here's what I want: c_list = C.objects.fiter(b__a__pk = pk_of_a_instance)

- Craig

- Craig

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.


Matt Schinckel

unread,
Dec 8, 2011, 5:46:42 PM12/8/11
to django...@googlegroups.com
Tip: have a teddy bear/rubber ducky/other toy that you can explain your problem too. They (probably) won't be able to solve it, but formulating it in a way to explain what is wrong to someone else is a great way to get more clarity on exactly what the problem is, and then solving it yourself.

Personally, I have an empty beer bottle I explain to, but that's because I always seem to have a surplus of empty beer bottles.
Reply all
Reply to author
Forward
0 new messages