[Django]-Do I need to optimize database access in django templates?

6👍

Queries in django are lazy, meaning that they try to resolve as little as possible until accessed. So right now you will hit the database for the store reference, and then again for the franchise ref. And that would be for each item in those results (many queries).

If you know you will need those relations, you can tell the query to get them all right away:

Items.objects.selected_related('store__franchise').all()

Django will do the joins ahead of time to make sure each result is already cached for those related objects. When you hit them, it will not trigger more queries.

More info on select_related here

A really cool way to test this out is to start the django shell ./manage.py shell, and look at the queries that get issued:

from django import db
from django.db import connection

db.reset_queries()

items = list(Items.objects.all())
print connection.queries

db.reset_queries()

items = list(Items.objects.selected_related('store__franchise').all())
print connection.queries
👤jdi

Leave a comment