Django汇总,计数总和

瓦伦丁

我有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查询中完成?如何?

豪尔赫·雷涛(Jorge Leitao)

如果我理解正确,则可以使用

Forum.objects.annotate(num_threads=Count('threads__id'),
                       num_posts=Count('threads__posts__id'))

这在一个数据库命中中产生了两个注释。

第一个计算论坛中所有线程的数量,第二个计算论坛中所有线程的所有帖子(假设athread作为ForeignKey Form,而apostForeignKeywith threads

确切的命名'threads__posts__id'取决于外键的名称,但是Django将在建议不正确的情况下吐出错误并给出建议。

PS您可以删除.all(),它什么也没做。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章