使用按日期分组的百分比注释查询集
Annotate queryset with percentage grouped by date
假设我有以下模型:
class Order(models.Model):
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE)
created_at = models.DateTimeField(auto_now_add=True)
我需要用按月分组的每个 category
的百分比(基于 created_at
字段)来注释 Order
查询集。我设法编写了一个查询来计算按月分组的每个 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
分组的计数。
是否可以使用 Django 的 ORM 获取按月分组的每个 category
的百分比?例如,如果我有以下数据:
MONTH | CATEGORY
Jan | 'A'
Jan | 'B'
Feb | 'A'
我想得到类似这样的东西:
[
(Jan, 'A', 0.5),
(Jan, 'B', 0.5),
(Feb, 'A', 1),
]
提前致谢。
按照 @ac2001 在评论中的建议,使用 Django 的 Window functions,我设法得到了我需要的东西。
使用示例模型并假设我想要按月分组的每个 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')
)
欢迎提出任何进一步简化的建议。
假设我有以下模型:
class Order(models.Model):
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE)
created_at = models.DateTimeField(auto_now_add=True)
我需要用按月分组的每个 category
的百分比(基于 created_at
字段)来注释 Order
查询集。我设法编写了一个查询来计算按月分组的每个 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
分组的计数。
是否可以使用 Django 的 ORM 获取按月分组的每个 category
的百分比?例如,如果我有以下数据:
MONTH | CATEGORY
Jan | 'A'
Jan | 'B'
Feb | 'A'
我想得到类似这样的东西:
[
(Jan, 'A', 0.5),
(Jan, 'B', 0.5),
(Feb, 'A', 1),
]
提前致谢。
按照 @ac2001 在评论中的建议,使用 Django 的 Window functions,我设法得到了我需要的东西。
使用示例模型并假设我想要按月分组的每个 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')
)
欢迎提出任何进一步简化的建议。