【问题标题】:The annotate with Sum seems doesn't work DjangoSum 的注释似乎不起作用 Django
【发布时间】:2020-08-21 07:18:00
【问题描述】:

有一个如下的 db (mysql) 表:

class AccountsInsightsHourly(models.Model):
    account_id = models.CharField(max_length=32, blank=True, null=True)
    spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True)
    date = models.IntegerField(blank=True, null=True)
    hour = models.IntegerField(blank=True, null=True)
    created_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'accounts_insights_hourly'
        unique_together = (('account_id', 'date', 'hour'),)
        ordering = ["account_id", "hour"]

有些数据保存在 db 中是这样的:

id  account_id    spend    date        hour   created_time 

1     1222         200     20200820    12      ....
1     1222         300     20200820    14      ....

我尝试获取每个帐户在指定日期的最大支出。

base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday). \
            annotate(yesterday_spend=Max("spend", output_field=FloatField())). \
            values("account_id", "yesterday_spend")

# I got results like below

<QuerySet [{'account_id': '1222', 'yesterday_spend': 200}, {'account_id': '1222', 'yesterday_s
pend': 300}]>




# expected result is 

<QuerySet [{'account_id': '1222', 'yesterday_spend': 300}>

如何使注释按预期工作?

更新

感谢ruddra 的帮助,正确的查询集应该是

base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday).values("account_id"). \
            annotate(yesterday_spend=Max("spend", output_field=FloatField())). \
            values("account_id", "yesterday_spend").\
            order_by()

interaction-with-default-ordering-or-order-by

【问题讨论】:

    标签: django


    【解决方案1】:

    你可以这样试试:

    base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday).values("account_id"). \
                annotate(yesterday_spend=Max("spend", output_field=FloatField())). \
                values("account_id", "yesterday_spend")
    

    它将生成一个GROUP_BY 查询,如下所示:

    'SELECT "accounts_insights_hourly"."account_id", MAX("accounts_insights_hourly"."spend") AS "yesterday_spend" FROM "accounts_insights_hourly" WHERE "accounts_insights_hourly"."date" = 2020-08-21 GROUP BY "accounts_insights_hourly"."account_id"'
    

    【讨论】:

    • 感谢回复,但它回复了我&lt;QuerySet [{'yesterday_spend': 200}, {'yesterday_spend': 300}]&gt;
    • 你能看到更新的答案吗?它应该返回查询:'SELECT "AccountsInsightsHourly"."account_id", MAX("AccountsInsightsHourly"."spend") AS "yesterday_spend" FROM "AccountsInsightsHourly" GROUP BY "AccountsInsightsHourly"."account_id"'
    • 仍然得到相同的结果,并且打印的sql query 显示分组依据是`GROUP BY accounts_insights_hourly.account_id, accounts_insights_hourly.`hour`` 这让我很困惑。
    • 感谢您的耐心等待,我在查询集末尾添加了order_by(),终于成功了。
    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2015-10-24
    • 2013-08-07
    • 1970-01-01
    • 2017-05-22
    • 2012-09-19
    • 2019-04-23
    相关资源
    最近更新 更多