Ohad
Ohad

Reputation: 1480

Caching Django SQL queries on foreign keys

I have a model which contains a foreign key to a different model:

class MyModel(models.Model):
   ...
   picture = models.ForeignKey(Picture)
   ...

Im my template, I have an instance of MyModel and in three different places I access it's picture attribute this way {{ mymodel.picture }}.

When I open the debug_toolbar I see that three different SQL queries were made to the database. Shouldn't Django cache the first query and serve it afterwards? Is it possible to do so?

Upvotes: 2

Views: 297

Answers (2)

Jingo
Jingo

Reputation: 3240

You can try the with tag {% with p = mymodel.picture %}...{% endwith %}, see here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#with

Upvotes: 1

Siva Arunachalam
Siva Arunachalam

Reputation: 7750

{% with picture = mymodel.picture %}

My Picture Size Large {{ picture }}
My Picture Size Medium {{ picture }}
My Picture Size Small  {{ picture }}

{% endwith %}

Upvotes: 2

Related Questions