這將是有意義的QuerySet aggregation method per-item, annotate(),有這樣的名字,因爲它標註(套)的聚合值給每個項目(模型實例)它的產量,像一個正常的場,例如:
# Build an annotated queryset
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
<Book: The Definitive Guide to Django>
>>> q[0].authors__count
2
# Interrogate the second object in the queryset
>>> q[1]
<Book: Practical Django Projects>
>>> q[1].authors__count
1
關於名稱:
註記的名字會自動從總的名稱派生函數和正在彙總的字段的名稱。
>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1
例如有:
context['videos'] = Videos.objects.annotate(view_count=Count('views')).order_by('-view_count')[100:]
你可以使用:
[video.view_count for video in context['videos']]
哪個should be the same as使用可以通過提供一個別名,當您指定的註解覆蓋此默認名稱values_list():
Videos.objects.annotate(view_count=Count('views')).values_list('view_count', flat=True)
而且類似於:
{% for video in videos %}
{{ video.view_count }}
{% endfor %}
這就是說,不同於普通字段,the order in which filters are applied matters,你已經被警告B)
不應該在該「上下文[視頻] = Videos.objects。 annotate(view_count = Count(views))。order_by(view_count)[:100]「be」context ['videos'] = Videos.objects.annotate(view_count = Count('views'))。order_by('view_count') [:100] 「請發佈您的實際代碼,並且不要錯過獲得幫助的機會 – jpic 2012-02-28 01:12:57