Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#29081 closed Cleanup/optimization (fixed)

Clarify QuerySet.select_related() example regarding "hitting the database"

Reported by: Дилян Палаузов Owned by: nobody
Component: Documentation Version: 2.0
Severity: Normal Keywords: select_related
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-related says:

… then a call to Book.objects.select_related('author_ _hometown').get(id=4) will cache the related Person and the related City:

b = Book.objects.select_related('author_ _hometown').get(id=4)
p = b.author         # Doesn't hit the database.
c = p.hometown       # Doesn't hit the database.

b = Book.objects.get(id=4) # No select_related() in this example.
p = b.author         # Hits the database.
c = p.hometown       # Hits the database.

This leaves the impression, that the first snipped does not hit the database and the second snippet hits twice the database.

I propose:

  • wring after b = Book.objects.select_related('author_ _hometown').get(id=4) the comment # Hits the database with INNER JOIN.
  • changing b = Book.objects.get(id=4) # No select_related() in this example. to b = Book.objects.get(id=4) # No select_related() in this example, hits the database.

Change History (4)

comment:1 by Дилян Палаузов, 7 years ago

Description: modified (diff)

comment:2 by Tim Graham, 7 years ago

Description: modified (diff)
Has patch: set
Summary: select_related and hitting the databaseClarify QuerySet.select_related() example regarding "hitting the database"
Triage Stage: UnreviewedAccepted

comment:3 by Tim Graham <timograham@…>, 7 years ago

Resolution: fixed
Status: newclosed

In e6f0e324:

Fixed #29081 -- Clarified comments in QuerySet.select_related() example.

comment:4 by Tim Graham <timograham@…>, 7 years ago

In bbc4a5a:

[2.0.x] Fixed #29081 -- Clarified comments in QuerySet.select_related() example.

Backport of e6f0e324e28bc7d0c125415de871466aa1f4b983 from master

Note: See TracTickets for help on using tickets.
Back to Top