Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A left outer reverse select_related in Django?

Imagine the following model:

class Parent(Model):     ...  class Child(Model)     father = ForeignKey(Parent)     ... 

Some parents have children, others do not (they're not parents in the real meaning, it's just a fictional name).

I would like to make the following query: I want to list all the Parents, and if they have children, bring me the children too. That would be the equivalent of a left outer join to Child table, that is:

select * from app_parent left join app_child on child_father_id=parent_id 

This way, when I invoke Parent.child_set in my template, I won't hit the database a gazillion times. Is there a way to do that? Thanks

like image 889
augustomen Avatar asked Jun 04 '10 15:06

augustomen


People also ask

What does Select_related do in Django?

In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. In this article, we will see how it reduces the number of queries and make the program much faster.

What's the difference between Select_related and Prefetch_related in Django ORM?

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object ( ModelA in the above example).


1 Answers

Starting from Django 1.4 prefetch_related does what you want.

Parent.objects.prefetch_related('child_set') 

Related(!) django docs : https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related.

like image 52
Gautier Hayoun Avatar answered Sep 27 '22 23:09

Gautier Hayoun