python - 如何从数据库生成每日/每周/每月/每年汇总值

标签 python django django-rest-framework orm

我正在使用 Django Rest Framework 开发 API。我想生成每日/每周/每月/每年已发生的总预订的汇总值

我添加了一张图像来展示每周汇总数据的外观。这是简化模型。我尝试的大多数查询都未能达到我想要的效果。

class Booking(models.Model):
    trans_date = models.DateTime(auto_now_add=True)
    amount_paid = models.DecimalField(decimal_places=2, max_digits=20)
    trans_date = models.DateField(auto_now=True)

这是我尝试的查询;

weekly_agg = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('trans_date').annotate(count=Count('id')).values('trans_date','count')

enter image description here

最佳答案

这是解决方案,您可以适本地替换每日、每周等计数的变量:

from django.db.models.functions import ExtractDay,ExtractWeek,..Month,..Year
from django.db.models import Count

weekly_aggregate = Booking.objects.annotate(week=ExtractWeek('trans_date')).values('week').annotate(count=Count('id')).values('week'
,'count')

#output
<QuerySet [{'week': 3, 'count': 2}, {'week': 7, 'count': 7}, {'week': 20, 'count': 1}, {'week': 19, 'count': 1}, {'week': 1, 'count': 1}]>

关于python - 如何从数据库生成每日/每周/每月/每年汇总值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60315988/

相关文章:

django-rest-framework - 如何使用 Django Rest auth/all auth 连接帐户?

Python/Django 和阿拉伯文文档搜索应用程序

python - 将 sklearn scaler 对象保存到 json 而不是酸洗

python - PySpark:TypeError:条件应为字符串或列

python - 设置或更改类的属性时如何在 Django 中设置时间戳

django - 不将 Django Admin 与 Django Rest Framework 一起使用的原因是什么

python - 针对可以在多个组织中担任角色的用户的模型设计

python - 从Django项目实现对外部API的异步请求?

python - Django max_length 另一个模型属性

django - 如何将 django 网站分解为微服务