【Django聚合运算】annotate计算多个结果,有重复

1. 多个外键关联计算

 

Topic关联到TopicContent和TopicUser两种表,reply_count计算TopicContent关联到Topic的计数。

up_count 计算TopicUser中IsUp字段总和。

 

lTopicCounts = Topic.objects.filter(id=pId).annotate(reply_count=Count('fkTopicContentidTopic2Topic',distinct=True),\
                    up_count=Sum('fkTopicUseridTopic2Topic__IsUp',distinct=True),\
                    reward_sum=Sum('fkTopicUseridTopic2Topic__Reward',distinct=True),\
                    collect_count=Sum('fkTopicUseridTopic2Topic__IsCollect',distinct=True))

 

但是计算结果异常。

image

 

实际的up_count应该为1,TopicUser中只有一条记录。

https://docs.djangoproject.com/en/dev/topics/db/aggregation/中描述

 

For most aggregates, there is no way to avoid this problem, however, the Count aggregate has a distinctparameter that may help:

 

针对Sum方法,估计没有办法直接解决

于是将两张表的外键分开计算。

 

2. 分步计算

 

reply_count先计算

image

 

 

TopicUser表中的其他相关统计分开计算,注意的是,如果关联的TopicUser为空,则计算结果为None,需要做特殊处理

image

转载于:https://www.cnblogs.com/inns/p/5589846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值