Reputation: 10132
I saw this example from Django documentation on how to use select_related()
:
from django.db import models
class City(models.Model):
# ...
pass
class Person(models.Model):
# ...
hometown = models.ForeignKey(City)
class Book(models.Model):
# ...
author = models.ForeignKey(Person)
Then a call to Book.objects.select_related('person', 'person__city').get(id=4)
will cache the related Person
and the related City
.
I do not understand the exact query
that is made here. I understand the query
result
is pre-populated. but what query
( in english or sql
terms) is made here.
Upvotes: 1
Views: 469
Reputation: 6767
To show the exact query it will do, use this in the shell:
print Book.objects.select_related('person', 'person__city').get(id=4).query
Upvotes: 0
Reputation: 31252
As you mentioned it pre-populates the querySet
. That is, when the record is retrieved, it hits the database
only once. If you do not have select_related
, you will be making database
calls to Book,Person and City
individually, increasing the number of calls made from 1 to 3.
Upvotes: 1