eagertoLearn
eagertoLearn

Reputation: 10132

how does this select_related work in Django?

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

Answers (2)

Ben
Ben

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

brain storm
brain storm

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 databasecalls to Book,Person and City individually, increasing the number of calls made from 1 to 3.

Upvotes: 1

Related Questions