本文介绍 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
调用相比,这可以显著提高速度。
相关用法
- Python Sympy Prufer.prufer_rank()用法及代码示例
- Python Sympy Prufer.edges()用法及代码示例
- Python Sympy Prufer.to_tree()用法及代码示例
- Python Sympy Prufer.size()用法及代码示例
- Python Tableau ProjectItem用法及代码示例
- Python Sympy Prufer.unrank()用法及代码示例
- Python Sympy Prufer.tree_repr()用法及代码示例
- Python Sympy Prufer.rank()用法及代码示例
- Python Sympy Prufer.next()用法及代码示例
- Python Sympy Prufer.prev()用法及代码示例
- Python Sympy Prufer.nodes()用法及代码示例
- Python Sympy Prufer.prufer_repr()用法及代码示例
- Python Sympy Prufer.to_prufer()用法及代码示例
- Python Sympy Permutation.list()用法及代码示例
- Python Pandas Panel.add()用法及代码示例
- Python Pgmagick edge()用法及代码示例
- Python Pandas TimedeltaIndex.memory_usage用法及代码示例
- Python Pandas DatetimeIndex.day用法及代码示例
- Python PyTorch cos()用法及代码示例
- Python Pytorch logspace()用法及代码示例
- Python PyTorch is_storage()用法及代码示例
- Python Pandas Series.ne()用法及代码示例
- Python Pandas Series.dt.days_in_month用法及代码示例
- Python Pandas DataFrame.nsmallest()用法及代码示例
- Python Pandas Index.argmax()用法及代码示例
注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.db.models.Prefetch。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。