zoukankan      html  css  js  c++  java
  • 【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

    好记性不如烂笔头
  • 相关阅读:
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    免费的论文查重网站
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的HBase操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
  • 原文地址:https://www.cnblogs.com/inns/p/5589846.html
Copyright © 2011-2022 走看看