5

Let’s say that I have a class Child linked, through a FK, to another class Parent. Now let’s say I have a block of code doing something like this in a template

<td>{{ child.parent.name }}</td>
<td>{{ child.parent.age}}</td>
<td>{{ child.parent.address }}</td>

My first question is, will Django go to the database and read the Parent entity three times? My second question is: if yes, what is the best practice not to read it multiple times? I mean I know I can declare an object before this block and set it equal to child.parent but is there another way to do that?

Y2H
  • 2,419
  • 1
  • 19
  • 37

3 Answers3

5

No, Django will hit DB only once, next call will use cached attribute and will not requred access to DB, you can check related part of documentation.

But you can impove this by using select_related method, in this case even first call will not hit DB, since child.parent will be precached.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
3

Use select_related

In your view, get the Child objects like this:

children = Child.objects.select_related('parent').all()
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
1

To complement neverwalkaloner's answer, you can also alias child.parent in your template to avoid the lookup cost:

{% with parent=child.parent %}
<td>{{ parent.name }}</td>
<td>{{ parent.age}}</td>
<td>{{ parent.address }}</td>
{% endwith %}
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118