Joining different models in Django
Posted
by Andrew Roberts
on Stack Overflow
See other posts from Stack Overflow
or by Andrew Roberts
Published on 2010-04-30T17:56:44Z
Indexed on
2010/04/30
19:37 UTC
Read the original article
Hit count: 308
Let's say I have this data model:
class Workflow(models.Model):
...
class Command(models.Model):
workflow = models.ForeignKey(Workflow)
...
class Job(models.Model):
command = models.ForeignKey(Command)
...
Suppose somewhere I want to loop through all the Workflow objects, and for each workflow I want to loop through its Commands, and for each Command I want to loop through each Job. Is there a way to structure this with a single query?
That is, I'd like Workflow.objects.all()
to join in its dependent models, so I get a collection that has dependent objects already cached, so workflows[0].command_set.get() doesn't produce an additional query.
Is this possible?
© Stack Overflow or respective owner