Sum computed column in Django QuerySet

拜拜、爱过 提交于 2020-01-04 14:29:09

问题


Given the following Contribution model:

class Contribution(models.Model):
    start_time = models.DateTimeField()
    end_time = models.DateTimeField(null=True)

is it possible, using the Django database API, to reproduce the following SQL statement?

SELECT SUM(end_time - start_time) AS total_duration FROM contribution;

I've figured out this much:

Contribution.objects.aggregate(total_duration=models.Sum( ??? ))

but I'm not sure about how to represent the end_time - start_time part. Thanks!


回答1:


Not possible at the moment, there's a ticket for F() objects inside aggregation, but nothing promising.

The only way i see is to workaround by sum in python:

sum([x[1]-x[0] for x in Contribution.objects.values_list('start_time', 'end_time')])


来源:https://stackoverflow.com/questions/2424471/sum-computed-column-in-django-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!