如何使用 django ORM 聚合计算字段? (没有原始 SQL)
我试图找到某些事件的累积持续时间,“开始”和“结束”字段都是 django.db.models.DateTimeField 字段。
我想做的应该这样写:
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.
我无法分别聚合(求和)开始和结束,然后在 python 中减去,因为 DB 无法对 DateTime 对象求和。
没有原始 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有 Delorean 就无法帮助 Christophe,但我遇到了这个错误,并且能够在 Django 1.8 中解决它,例如:
当我无法将所有依赖项升级到 1.8 时,我发现这可以与 Django 1.7.9 一起使用MySQL 的:
Can't help Christophe without a Delorean, but I was hitting this error and was able to solve it in Django 1.8 like:
When I couldn't upgrade all my dependencies to 1.8, I found this to work with Django 1.7.9 on top of MySQL:
如果您使用的是 Postgres,那么您可以使用 django-pg-utils 包并计算在数据库中。将持续时间字段转换为秒,然后求和
If you are on Postgres, then you can use the django-pg-utils package and compute in the database. Cast the duration field into seconds and then take the sum
这个答案还没有真正让我满意,我当前的工作是有效的,但它不是数据库计算的...
它返回查询集中所有事件的持续时间(以秒为单位)
更好的更少 SQL 的解决方案?
This answer don't realy satisfy me yet, my current work around works but it's not DB computed...
It returns the duration of all events in the queryset in seconds
Better SQL less solutions?