我正在使用 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')
最佳答案
这是解决方案,您可以适本地替换每日、每周等计数的变量:
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/