Hanpan
Hanpan

Reputation: 10251

Django - How can I stop this repeat query?

So I am trying to retrieve a list of blog entries, which has a foreign key to the author:

In my view:

data = {'entries':Entry.objects.all()}

Then in my template:

<td valign="top">{{ entry.author }}</td>

This is hitting the database once per entry to get the authors details. I understand this, but when the author is the same, is there any way to 'cache' the result? For example, if one entry has an author 'relationship' of 1, can I store the results so if any other entries have the same author 'relationship', it doesn't need to hit the database again?

I'm sure this must be possible but I can't find mention of it in the documentation :(

Upvotes: 0

Views: 317

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799180

No. But you can use QuerySet.select_related() to pull in the FK information at the same time.

Upvotes: 6

Related Questions