如何使用django ORM聚合计算字段? (没有原始SQL) [英] How to aggregate computed field with django ORM? (without raw SQL)
问题描述
我试图找到一些事件累积的持续时间,'开始'和'结束'字段都是 django.db.models.DateTimeField
字段。 p>
我想做的应该是这样写的:
从django.db.models import F,Sum
from my.models import Event
Event.objects.aggregate(anything = Sum(F('start') - F('end'))
#这个第一个例子返回:
#AttributeError:'ExpressionNode'对象没有属性'split'
#Ok我会尝试更多SQLish:
Event.objects $($)
#此时间:
#FieldError:($)
#这个时间:
'extra_field':'开始 - 结束'
}无法将关键字'extra_field'解析为字段。
我不能agreggate(Sum)开始和结束分开,然后在python中减法,因为DB不能Sum DateTime对象。
没有原始sql的好方法?
这个答案不是真的满足了我,我目前的工作,但它不是DB计算...
reduce(lambda h,e:h +(e.end - e.start).total_seconds(),event,0)
它以秒为单位返回查询中所有事件的持续时间。
更好的SQL少解决方案?
I'm trying to find the cumulated duration of some events, 'start' and 'end' field are both django.db.models.DateTimeField
fields.
What I would like to do should have been written like this:
from django.db.models import F, Sum
from my.models import Event
Event.objects.aggregate(anything=Sum(F('start') - F('end')))
# this first example return:
# AttributeError: 'ExpressionNode' object has no attribute 'split'
# Ok I'll try more SQLish:
Event.objects.extra(select={
'extra_field': 'start - end'
}).aggregate(Sum('extra_field'))
# this time:
# FieldError: Cannot resolve keyword 'extra_field' into field.
I can't agreggate (Sum) start and end separately then substract in python because DB can't Sum DateTime objects.
A good way to do without raw sql?
This answer don't realy satisfy me yet, my current work around works but it's not DB computed...
reduce(lambda h, e: h + (e.end - e.start).total_seconds(), events, 0)
It returns the duration of all events in the queryset in seconds
Better SQL less solutions?
这篇关于如何使用django ORM聚合计算字段? (没有原始SQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!