【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

posted @ 2016-06-16 09:20  inns  阅读(1696)  评论(0编辑  收藏  举报