Say I have 3 models:
class Franchises
name = models.CharField()
class Stores
franchise = models.ForeignKey(Franchises)
name = models.CharField()
class Items
store = models.ForeignKey(Stores)
name = models.CharField()
in view
items = Items.objects.all()
in template
{% for item in items %}
<div>item.store.franchise.name</div>
{% endfor %}
I wonder whether executing item.store.franchise.name will hit the database? and what I need to do to optimize the database access?
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
storereference, and then again for thefranchiseref. 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:
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: