gpt4 book ai didi

python - Django 聚合,计数总和

转载 作者:太空狗 更新时间:2023-10-30 02:31:01 25 4
gpt4 key购买 nike

我有 3 个模型:论坛、主题、帖子,我正在创建一个 View 来显示论坛列表。但我还想显示每个论坛的线程数和帖子数。

然后我必须:

  • 计算每个线程的帖子数
  • 对每个论坛的每个线程的帖子计数求和

我在这里找到了类似的东西: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 查询中完成?怎么办?

最佳答案

如果我没理解错的话,你可以使用

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

这使得一次数据库命中中有两个注释。

第一个计算论坛上的所有线程,第二个计算论坛所有线程上的所有帖子(假设一个 thread 是一个具有 Form 的 ForeignKey,一个 发布一个带有线程ForeignKey

'threads__posts__id' 中的确切命名取决于外键的名称,但如果它们不正确,Django 会吐出错误并给出建议。

附言你可以删除 .all(),它什么都不做。

关于python - Django 聚合,计数总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24076893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com