class Prefetch(lookup, queryset=None, to_attr=None)
[source]
The Prefetch()
object can be used to control the operation of prefetch_related()
.
The lookup
argument describes the relations to follow and works the same as the string based lookups passed to prefetch_related()
. For example:
>>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() <QuerySet [<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() <QuerySet [<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 select_related()
from the prefetched relation, hence reducing the number of queries even further:
>>> voted_choices = Choice.objects.filter(votes__gt=0) >>> voted_choices <QuerySet [<Choice: The sky>]> >>> prefetch = Prefetch('choice_set', queryset=voted_choices) >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() <QuerySet [<Choice: The sky>]>
The to_attr
argument sets the result of the prefetch operation to a custom attribute:
>>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices') >>> Question.objects.prefetch_related(prefetch).get().voted_choices <QuerySet [<Choice: The sky>]> >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
Note
When using to_attr
the prefetched result is stored in a list. This can provide a significant speed improvement over traditional prefetch_related
calls which store the cached result within a QuerySet
instance.
Please login to continue.