【发布时间】:2014-07-27 10:22:42
【问题描述】:
我有 3 个模型:论坛、主题、帖子,我正在创建一个视图来显示论坛列表。但我也想显示每个论坛的线程数和帖子数。
然后我必须:
- 统计每个主题的帖子数
- 汇总每个论坛每个主题的帖子数
我在这里找到了类似的东西:Django: Sum the count of a sub sub foreign object 但答案对我不起作用。
from django.shortcuts import render
from django.template import Context
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from chinwag.models import Forum, Thread, Post
@login_required
def forums(request):
forums = Forum.objects.annotate(num_posts=Count('threads__posts')).all(
).select_related('threads__last_post')
return render(request, 'chinwag/forums.html', Context({
'forums': forums,
}))
是否可以在 1 个 SQL 查询中完成?怎么样?
【问题讨论】:
标签: python sql database django aggregate