如何在 Django ORM 中使用注释和聚合总和的组合
How to use combination of annotate and aggregate sum in Django ORM
从下面table我需要的输出有,
[(Apple,21.0), (Orange,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()
您可以通过以下方式使用 GROUP BY:
from django.db.models import <strong>Sum</strong>
Fruits.objects.filter(
date__range=(quarter_start_date, quarter_end_date)
).values('item').annotate(
<strong>total=Sum('price')</strong>
).order_by('item')
这将生成一个如下所示的查询集:
<QuerySet [
{'item': 'Apple', 'total': 21.0},
{'item': 'Grapes', 'total': 15.0},
{'item': 'Orange', 'total': 12.0}
]>
一个字典集合,其中键 'item'
和 total
映射到项目以及满足给定条件的 item
的所有 price
的总和日期时间范围。
不过,我建议制作一个 FruitItem
模型并使用 ForeignKey
,将您的数据库建模转换为 Third Normal Form [wiki]。
从下面table我需要的输出有,
[(Apple,21.0), (Orange,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()
您可以通过以下方式使用 GROUP BY:
from django.db.models import <strong>Sum</strong>
Fruits.objects.filter(
date__range=(quarter_start_date, quarter_end_date)
).values('item').annotate(
<strong>total=Sum('price')</strong>
).order_by('item')
这将生成一个如下所示的查询集:
<QuerySet [
{'item': 'Apple', 'total': 21.0},
{'item': 'Grapes', 'total': 15.0},
{'item': 'Orange', 'total': 12.0}
]>
一个字典集合,其中键 'item'
和 total
映射到项目以及满足给定条件的 item
的所有 price
的总和日期时间范围。
不过,我建议制作一个 FruitItem
模型并使用 ForeignKey
,将您的数据库建模转换为 Third Normal Form [wiki]。