django - 使用按日期分组的百分比注释查询集
问题描述
假设我有以下模型:
class Order(models.Model):
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE)
created_at = models.DateTimeField(auto_now_add=True)
我需要使用按月分组Order
的每个查询集的百分比category
(基于created_at
字段)来注释查询集。我设法编写了一个查询来计算Order
按月分组的每个:
orders_per_month = (Order.objects
.annotate(month=TruncMonth('created_at'))
.values('month')
.annotate(count=Count('id'))
.order_by('month')
.values('month', 'count')
)
将最后一个更改.values()
为.values('month', 'category', 'count')
,我可以得到按category
和分组的计数month
。
category
是否可以使用 Django 的 ORM 获得每个按月分组的百分比?例如,如果我有以下数据:
MONTH | CATEGORY
Jan | 'A'
Jan | 'B'
Feb | 'A'
我想得到类似的东西:
[
(Jan, 'A', 0.5),
(Jan, 'B', 0.5),
(Feb, 'A', 1),
]
提前致谢。
解决方案
正如@ac2001 在评论中所建议的那样,使用 Django 的Window 函数,我设法得到了我需要的东西。
使用示例模型并假设我希望每个category
按月分组的百分比:
orders_per_month = (Order.objects
.annotate(month=TruncMonth('created_at'))
.values('month', 'category')
.distinct()
.annotate(month_total=Window(
expression=Count('id'),
partition_by=[F('month')],
))
.annotate(month_category=Window(
expression=Count('id'),
partition_by=[F('month'), F('category')],
))
.annotate(percentage=ExpressionWrapper(
F('month_category') * 100.0 / F('month_total'),
output_field=FloatField()
))
.values('month', 'percentage', 'category')
)
欢迎任何有关进一步简化的建议。
推荐阅读
- arduino - 用 long int 的最后一个值增加当前值 - arduino
- html - 如何修复引号的编码?
- c# - 如何在 C# 中使用 Xceed 删除 Word 文件的相关人员(作者和修改者)属性
- python - 在堆叠(多层)LSTM 中,隐藏状态 [h,c] 如何处理?
- c - NSString 字符串格式说明符问题
- python - MJPG格式的Opencv无关字节
- java - 在树网格 vaadin 的叶子之间添加数据
- python - read_train_sets() 缺少 1 个必需的位置参数:“类”
- java - 有人会在这种情况下解释“类型不匹配:无法从双精度转换为布尔值”吗?
- html - 如何根据拨动开关设置使元素消失