diff options
| author | Sean Wang <sean@decrypted.org> | 2015-03-09 22:17:33 -0700 |
|---|---|---|
| committer | Simon Charette <charette.s@gmail.com> | 2015-03-11 12:39:50 -0400 |
| commit | e0e2df412f530d186e35016d0a920a03b508ddd1 (patch) | |
| tree | 437be3454b4b3951fa1b0a4f9c15311fd94a97ff /docs/ref | |
| parent | 2982143dac244b5d9b49bf65380394f9c6866dd9 (diff) | |
[1.8.x] Fixed #24414 -- Added examples of Prefetch object usage to the docs.
Backport of a3e89f13dfb1f22a26ead8b06b37695598a4421a from master
Diffstat (limited to 'docs/ref')
| -rw-r--r-- | docs/ref/models/querysets.txt | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index 2f3168c83e..7ffc54e9da 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -2906,15 +2906,35 @@ The ``Prefetch()`` object can be used to control the operation of The ``lookup`` argument describes the relations to follow and works the same as the string based lookups passed to -:meth:`~django.db.models.query.QuerySet.prefetch_related()`. +:meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example: + + >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() + [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] + # This will only execute two queries regardless of the number of Question + # and Choice objects. + >>> Question.objects.prefetch_related(Prefetch('choice_set')).all() + [<Question: Question object>] The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup. This is useful to further filter down the prefetch operation, or to call :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched -relation, hence reducing the number of queries even further. +relation, hence reducing the number of queries even further: + + >>> voted_choices = Choice.objects.filter(votes__gt=0) + >>> voted_choices + [<Choice: The sky>] + >>> prefetch = Prefetch('choice_set', queryset=voted_choices) + >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() + [<Choice: The sky>] The ``to_attr`` argument sets the result of the prefetch operation to a custom -attribute. +attribute: + + >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices') + >>> Question.objects.prefetch_related(prefetch).get().voted_choices + [<Choice: The sky>] + >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() + [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] .. note:: |
