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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With