我有以下型号:
class Order(models.Model):
some fields
class OrderStatus(models.Model):
order = models.ForiegnKey(Order)
status = models.CharField(choices=['ORDERED', 'RECEIVED'])
time = models.DateTimeField()
使用Django ORM,如何将(平均)周转时间(TAT)聚合到单个时间段?
例如(伪代码):
Order0 (TAT=12 hours)
OrderStatus0: order=Order0, status=ORDERED, time=00:00 8/24/16
OrderStatus1: order=Order0, status=RECEIVED, time=12:00 8/24/16
Order1 (TAT=24 hours)
OrderStatus2: order=Order1, status=ORDERED, time=04:00 8/24/16
OrderStatus3: order=Order1, status=RECEIVED, time=04:00 8/25/16
Average TAT = 18 hours
Pseudo-SQL看起来像这样:
Order
tat = Average
Subtract
OrderStatus.status_time
where status=RECEIVED
OrderStatus.status_time
where status=ORDERED
我尝试过使用Aggregate()
,Annotate()
,F()
,Q()
,When
和Case
的组合,但可以&# 39;达到解决方案,因为我需要在聚合内部查询OrderStatus 。
以下是非工作尝试:
Order.objects.aggregate(
Avg(
F('order__orderstatus__status_time') -
F('order__orderstatus__status_time')))
仅供参考,我使用的是Django 1.9和Postgresql 9.3