1

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.

eagertoLearn
  • 9,772
  • 23
  • 80
  • 122

2 Answers2

1

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.

brain storm
  • 30,124
  • 69
  • 225
  • 393
0

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
Ben
  • 6,687
  • 2
  • 33
  • 46