Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling foreign key object several times in Django without several DB requests

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?

like image 504
Y2H Avatar asked Jan 29 '23 04:01

Y2H


1 Answers

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.

like image 83
neverwalkaloner Avatar answered Jan 31 '23 11:01

neverwalkaloner