【问题标题】:How to add sum of annotate to a column of the original model如何将注释总和添加到原始模型的列
【发布时间】:2020-08-04 09:08:46
【问题描述】:

示例模型:

class Cluster(models.Model):
    index = models.BigIntegerField(blank=True, null=True)
    cluster_id = models.BigIntegerField(blank=True, null=True)
    module_count = models.BigIntegerField(blank=True, null=True)

我知道我可以通过以下方式获得 django 模型的 groupby 总和:

    cluster_id | module_count 
    -------------------------
    1          | 1
    1          | 2
    2          | 3
    2          | 1
 

    sum_mods = clusters.values('cluster_id').annotate(data_sum=Sum('module_count'))


    cluster_id | module_count 
    -------------------------
    1          | 3
    2          | 4

这会给我按 cluster_id 分组的每组的总和。

如何将此总和分配给原始模型中的列?如:

    cluster_id | module_count | data_sum 
    ----------------------------------------
    1          | 1            |3
    1          | 2            |3
    2          | 3            |4
    2          | 1            |4

【问题讨论】:

  • 添加您的模型
  • 模型添加到顶部

标签: sql django django-models group-by sum


【解决方案1】:

试试这个

clusters.values('cluster_id').update(data_sum=Sum('module_count'))

【讨论】:

  • 这给出了“此查询中不允许聚合函数”错误
【解决方案2】:
pk_list = list(set(Cluster.objects.all().values_list('cluster_id', flat=True)))
#return list of all unique cluster_id

for pk in pk_list:
    #get all cluster with this id
    lst = Cluster.objects.filter(cluster_id=pk)

    #get sum of all module_count
    sum_col = lst.aggregate(sum_col=Sum('module_count'))['sum_col']

    #update  all cluster with sum_col
    lst.update(module_count=sum_col)

【讨论】:

  • 我得到:AttributeError: 'OuterRef' object has no attribute 'annotate'
  • Sorry Iment "AttributeError: 'OuterRef' object has no attribute 'aggregate'"
  • 是的,抱歉,缺少一个括号,我正在编辑我的帖子,现在检查;)
  • 还没有运气:ValueError:此查询集包含对外部查询的引用,只能在子查询中使用。
  • 我已经更新它并且可以工作(用假数据库和你的模型测试),没有经过中继优化(许多 sql 请求,我会尝试其他“异国情调”查询),如果找到我会回来最佳解决方案;)
猜你喜欢
  • 2017-10-18
  • 2017-04-28
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
相关资源
最近更新 更多