当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Django Prefetch用法及代码示例


本文介绍 django.db.models.Prefetch 的用法。

声明

class Prefetch(lookup, queryset=None, to_attr=None)

Prefetch() 对象可用于控制 prefetch_related() 的操作。

lookup 参数说明了要遵循的关系,其工作方式与传递给 prefetch_related() 的基于字符串的查找相同。例如:

>>> from django.db.models import Prefetch
>>> 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: What's up?>]>

queryset 参数为给定的查找提供一个基本的QuerySet。这有助于进一步过滤预取操作,或从预取关系中调用 select_related() ,从而进一步减少查询数量:

>>> 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>]>

to_attr 参数将预取操作的结果设置为自定义属性:

>>> 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()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

注意

使用to_attr 时,预取结果存储在列表中。与将缓存结果存储在 QuerySet 实例中的传统 prefetch_related 调用相比,这可以显著提高速度。

相关用法


注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.db.models.Prefetch。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。