select_related between three or more models
Question:
When using select_related in Django, you can get from A to B
to a foreign key, you would write the following
A.objects.select_related('B')...
What should I write if I am referencing a foreign key from B to C?
Answers:
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:
A.objects.select_related('B__C')
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.
When using select_related in Django, you can get from A to B
to a foreign key, you would write the following
A.objects.select_related('B')...
What should I write if I am referencing a foreign key from B to C?
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:
A.objects.select_related('B__C')
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.