【问题标题】:How to use combination of annotate and aggregate sum in Django ORM如何在 Django ORM 中使用注释和聚合总和的组合
【发布时间】:2022-01-03 11:36:38
【问题描述】:

从下表中我需要输出有,

[(Apple,21.0), (Or​​ange,12.0) ,(Grapes,15.0)]

基本上是用它们的成本总和分组的水果

日期在 (dd/mm//yyyy)

Fruits Table
date        item    price
01/01/2021  Apple   5.0
01/01/2021  Orange  2.0
01/01/2021  Grapes  3.0
01/02/2021  Apple   7.0
01/02/2021  Orange  4.0
01/02/2021  Grapes  5.0
01/03/2021  Apple   9.0
01/03/2021  Orange  6.0
01/03/2021  Grapes  7.0
...........
....

models.py

 class Fruits(models.Model):
        item = models.CharField(max_length=32)
        date = models.DateField()
        price = models.FloatField()

我试过下面的代码它没有按预期工作

fruit_prices = Fruits.objects.filter(date__gte=quarter_start_date,date__lte=quarter_end_date)
               .aggregate(Sum('price')).annotate('item').values('item','price').distinct()

【问题讨论】:

  • 可以分享模型吗?
  • 过滤看起来也很奇怪:quarter_start_date 被使用了两次?
  • 抱歉日期__lte=quarter_end_date
  • 你能分享你的模型(相关部分)吗?
  • @WillemVanOnsem 添加模型

标签: python python-3.x django django-models django-views


【解决方案1】:

您可以通过以下方式使用 GROUP BY:

from django.db.models import Sum

Fruits.objects.filter(
    date__range=(quarter_start_date, quarter_end_date)
).values('item').annotate(
    total=Sum('price')
).order_by('item')

这将生成一个如下所示的查询集:

<QuerySet [
    {'item': 'Apple', 'total': 21.0},
    {'item': 'Grapes', 'total': 15.0},
    {'item': 'Orange', 'total': 12.0}
]>

字典集合,其中键 'item'total 映射到项目以及满足给定日期时间范围的 item 的所有 prices 的总和。

不过,我建议制作 FruitItem 模型并使用 ForeignKey,将您的数据库建模转换为 Third Normal Form [wiki]

【讨论】:

  • 而不是 order_by('item') 它不应该是注释??
  • @SivaPerumal:是的。 total 应该在 .annotate(..) 子句中。忘记了 .values(..) 不适用于聚合。已更新。
猜你喜欢
  • 2021-01-20
  • 1970-01-01
  • 2016-01-30
  • 2023-03-29
  • 2018-08-19
  • 2019-09-14
  • 2011-07-07
  • 2016-10-06
  • 2019-11-15
相关资源
最近更新 更多