我有3个模型:Forum,Thread,Post,并且我正在创建一个视图以显示论坛列表。但我也想显示每个论坛的主题数和帖子数。
然后,我必须:
我在这里发现了类似的东西:Django:对sub sub异物的计数求和,但是答案对我不起作用。
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查询中完成?如何?
如果我理解正确,则可以使用
Forum.objects.annotate(num_threads=Count('threads__id'),
num_posts=Count('threads__posts__id'))
这在一个数据库命中中产生了两个注释。
第一个计算论坛中所有线程的数量,第二个计算论坛中所有线程的所有帖子(假设athread
作为ForeignKey Form
,而apost
为ForeignKey
with threads
。
确切的命名'threads__posts__id'
取决于外键的名称,但是Django将在建议不正确的情况下吐出错误并给出建议。
PS您可以删除.all()
,它什么也没做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句