【问题标题】:Django Aggregation, sum of countsDjango聚合,计数总和
【发布时间】: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


    【解决方案1】:

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

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

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

    第一个计算论坛上的所有线程,第二个计算论坛所有线程上的所有帖子(假设 thread 为 ForeignKey 和 Formpost ForeignKeythreads .

    'threads__posts__id' 中的确切命名取决于外键的名称,但如果建议不正确,Django 会报错。

    附:你可以删除.all(),它什么也没做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 2011-09-01
      • 2019-06-14
      • 2019-08-05
      • 1970-01-01
      • 2021-12-13
      • 2011-05-21
      • 2012-03-08
      相关资源
      最近更新 更多