Ticket #23732: 23732.diff

File 23732.diff, 1.5 KB (added by Tim Graham, 10 years ago)
  • docs/ref/models/querysets.txt

    diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt
    index 4143787..26b218e 100644
    a b And here's ``select_related`` lookup::  
    754754    # in the previous query.
    755755    b = e.blog
    756756
     757Here's another example that shows there is no need to use ``get()`` after
     758``select_related()`` (just in case you got that impression from the example
     759above)::
     760
     761    # Find all the blogs with entries scheduled to be published in the future.
     762    blogs = set()
     763
     764    for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
     765        # Without select_related(), this would make a database for each
     766        # loop iteration in order to fetch the related blog for each entry.
     767        blogs.add(e.blog)
     768
    757769You can follow foreign keys in a similar way to querying them. If you have the
    758770following models::
    759771
    following models::  
    771783        # ...
    772784        author = models.ForeignKey(Person)
    773785
    774 ... then a call to ``Book.objects.select_related('person__city').get(id=4)``
     786... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
    775787will cache the related ``Person`` *and* the related ``City``::
    776788
    777     b = Book.objects.select_related('person__city').get(id=4)
     789    b = Book.objects.select_related('author__hometown').get(id=4)
    778790    p = b.author         # Doesn't hit the database.
    779791    c = p.hometown       # Doesn't hit the database.
    780792
Back to Top