对Django QuerySet中的计算列求和 [英] Sum computed column in Django QuerySet
本文介绍了对Django QuerySet中的计算列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下贡献
模型:
class Contribution(models.Model):
start_time = models.DateTimeField()
end_time = models.DateTimeField(null=True)
是否可以使用Django数据库API重现以下SQL语句?
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;
我很清楚:
Contribution.objects.aggregate(total_duration=models.Sum( ??? ))
,但是我不确定如何表示 end_time-start_time
部分。谢谢!
but I'm not sure about how to represent the end_time - start_time
part. Thanks!
推荐答案
目前无法实现,有一个票证用于聚合内的F()对象,但没有希望。
Not possible at the moment, there's a ticket for F() objects inside aggregation, but nothing promising.
我唯一看到的方法是python中按总和的解决方法:
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')])
这篇关于对Django QuerySet中的计算列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文