select_related between three or more models


When using select_related in Django, you can get from A to B
to a foreign key, you would write the following


What should I write if I am referencing a foreign key from B to C?

Asked By: y.dai



If you want to use select_related to follow a foreign key relationship from A to C via B, you can chain the related field using double underscores, like this:


This will fetch the related B and C objects using an SQL join, which can help you avoid additional database queries when accessing the related objects later in your code.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.