【问题标题】:Django Annotate - Can I used the fields created in annotate for another field created in annotate?Django Annotate - 我可以将在 annotate 中创建的字段用于在 annotate 中创建的另一个字段吗?
【发布时间】:2021-01-30 11:08:17
【问题描述】:

我正在计算每个部门的分数总和以及注释中每个部门的用户数,如下所示:

queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True)).order_by('-total_pts')

我还想作为返回数据的一部分发回 avg_score = total_pts / total_users。有没有办法将它添加到注释中,或者将它们链接在一起,或者以其他方式将它添加到返回查询集中?

编辑:

我尝试添加如下内容:

queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True), avg_score=total_pts/total_users).order_by('-total_pts')

错误提示未定义 total_pts。

谢谢。

【问题讨论】:

  • 当前设置有什么问题?有错误吗?什么错误?也添加一个最小可验证示例

标签: django django-rest-framework django-orm


【解决方案1】:

用 F() 弄明白了,之前一直不太明白怎么用:

queryset = Depts.objects.annotate(total_pts=Sum('userprofiles__user__activity_user__activity_category__pts'), total_users=Count('userprofiles', distinct=True), avg_score=F('total_pts') / F('total_users')).order_by('-avg_score')

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 2021-07-12
    • 2011-04-23
    • 2017-01-15
    • 2021-01-30
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多