當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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