Django Variable Re-evaluation in Template

So let's say in my models, I use:

def Model1(models.Model):
   model2 = models.ForeignKey(Model2)

def Model2(models.Model):
   model3 = models.ForeignKey(Model3)

def Model3(models.Model):
   code1 = models.CharField(max_length=150)
   code2 = models.CharField(max_length=150)
   code3 = models.CharField(max_length=150)
   code4 = models.CharField(max_length=150)
   code5 = models.CharField(max_length=150)
   code6 = models.CharField(max_length=150)
   code7 = models.CharField(max_length=150)

And in the template:

<td> {{ model1.model2.model3.code1 }} </td>
<td> {{ model1.model2.model3.code2 }} </td>
<td> {{ model1.model2.model3.code3 }} </td>
<td> {{ model1.model2.model3.code4 }} </td>
<td> {{ model1.model2.model3.code5 }} </td>
<td> {{ model1.model2.model3.code6 }} </td>
<td> {{ model1.model2.model3.code7 }} </td>

and for comparison:

{% with col=model1.model2.model3 %}
   <td> {{ col.code1 }} </td>
   <td> {{ col.code2 }} </td>
   <td> {{ col.code3 }} </td>
   <td> {{ col.code4 }} </td>
   <td> {{ col.code5 }} </td>
   <td> {{ col.code6 }} </td>
   <td> {{ col.code7 }} </td>
{% endwith %}

In the view, I don't use select_related.

My questions are:

  1. For the first code, does it imply that the model1.model2.model3 will be queried by Django 7 times?
  2. For the second code, will the usage of with col=model1.model2.model3 can make the template rendering faster, as the query of model1.model2.model3 is only once from the {% with %} block, and just get the variables from the col?
  3. Are there any alternatives to both these approaches?

Currently, my SQL table consists of less than 1000 rows so any performance issues may not be seen. But, my concern is when the SQL table is large enough and will require many optimization on the query.

  1. Yes, If you don't cache the result of the query or any other custom manager or ..., Django ORM will execute the question every time you call it, for more information on this you can read "When QuerySets are evaluated" in official documents.
  2. This is a better way than the first one because as you said you hit the database only once and save the result to use over and over.
  3. It depends on what you want to do, if it shouldn't be real-time you can use the cache, or you can write a function in model1 and return what you want from that function then you can do more in it (considering documentation that I've mentioned earlier to do what you want in only one query)
Back to Top