How to fetch all child related objects in a single query in Django?
For example we have 3 models:
class Parent(models.Model):
...
class Child(models.Model):
parent = models.ForeignKey(Parent)
class SubChild(models.Model):
parent = models.ForeignKey(Child)
I want to fetch all the data in a single query like this:
select * from parent p join child c on c.parent_id = p.id join subchild sc on sc.parent_id = c.id
How I could perform this using Django ORM? What if I will have multiple child models? In SQL I just add more joins, but how I could do it in Django?
Now I have few seconds delay when load everything recursively with multiple queries. The prefetch_related method does not help, I mean
qs = Parent.objects.all().prefetch_related('child').prefetch_related('child__subchild')
for parent in qs:
# here I need to access parent.childs.all() and child.subchild.all() without new queries