本文介紹 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。