summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorTim Graham <timograham@gmail.com>2014-10-31 15:38:46 -0400
committerTim Graham <timograham@gmail.com>2014-10-31 15:40:34 -0400
commite876c7f1ee4e0f071f7920b729829a3373ce2a9b (patch)
tree75cfd8ff0adb44ddc279bacf4ac80f533ccb025a /docs
parentc2cad66e4743afa28b3bf476e62aae29cc8abc47 (diff)
[1.7.x] Fixed #23732 -- Corrected and enhanced select_related() docs.
Thanks Daniele Procida for the report and review. Backport of e958c760f9 from master
Diffstat (limited to 'docs')
-rw-r--r--docs/ref/models/querysets.txt22
1 files changed, 20 insertions, 2 deletions
diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
index 4143787958..9fe3b61eec 100644
--- a/docs/ref/models/querysets.txt
+++ b/docs/ref/models/querysets.txt
@@ -754,6 +754,24 @@ And here's ``select_related`` lookup::
# in the previous query.
b = e.blog
+You can use ``select_related()`` with any queryset of objects::
+
+ from django.utils import timezone
+
+ # Find all the blogs with entries scheduled to be published in the future.
+ blogs = set()
+
+ for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
+ # Without select_related(), this would make a database query for each
+ # loop iteration in order to fetch the related blog for each entry.
+ blogs.add(e.blog)
+
+The order of ``filter()`` and ``select_related()`` chaining isn't important.
+These querysets are equivalent::
+
+ Entry.objects.filter(pub_date__gt=timezone.now()).selected_related('blog')
+ Entry.objects.selected_related('blog').filter(pub_date__gt=timezone.now())
+
You can follow foreign keys in a similar way to querying them. If you have the
following models::
@@ -771,10 +789,10 @@ following models::
# ...
author = models.ForeignKey(Person)
-... then a call to ``Book.objects.select_related('person__city').get(id=4)``
+... 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('person__city').get(id=4)
+ 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.