class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
category = models.ForeignKey(
Category, null=True, on_delete=models.SET_NULL
)
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
placed = models.DateTimeField(auto_now=True)
shipped = models.DateTimeField(null=True)
delivered = models.DateTimeField(null=True)
我想计算每个类别的订单处理速度的统计数据其中处理时间为delivered - shipped
结果我想实现这样的目标:
[
{
"category": <category 1>
"processed_time": <average processed time in seconds>
},
{
"category": <category 2>
"processed_time": <average processed time in seconds>
},
{
"category": <category 3>
"processed_time": <average processed time in seconds>
},
]
我可以在ORM之外计算,但我想通过注释/聚合以某种方式实现这一点
delivered = delivered_qs.annotate(first_processed=Min("delivered"), last_processed=Max("delivered"))
.aggregate(processed_time=F("last_processed")-F("first_processed"))
这个QS只返回所有类别的时间,我不知道如何检索每个类别的时间
您想要做一个group by
,它在Django中的工作方式有点奇怪。有关更多信息,请参阅文档
但通过首先使用.values,您可以再次说出要在类别上分组的查询集。然后确定最小值、最大值和差值。
delivered = (
delivered_qs
.values('category')
.annotate(
first_processed=Min("delivered"),
last_processed=Max("delivered"),
processed_time=F("last_processed") - F("first_processed"),
)
)
在我看来,它会回来:
[{
"category": 1,
"first_processed": timedelta(),
"last_processed": timedelta(),
"processed_time": timedelta()
}, ...]