在sqlAlchemy中求和字段
我最近升级了sqlalchemy到最新版本,结果我的一些代码不再能正常工作了。我现在很难找到解决办法,希望能有人帮帮我。
之前查询的代码是这样的。
self.db.query(Drive).filter(Drive.package_id==package.package_id)\
.filter(Drive.wipe_end!=None).sum(Drive.wipe_end - Drive.wipe_start)
这个代码之前可以用来获取一些时间段的总和,但现在我遇到了以下错误:
'Query' object has no attribute 'sum'
我在网上搜索的信息都是几年前的,找不到最新的解决方案。
2 个回答
16
在SQLAlchemy 1.1.13版本(发布于2017年8月3日),使用sum()
的语法是这样的:
from sqlalchemy import func
from apps.mystuff.models import MyModel
some_value = "hello"
result = MyModel.query.with_entities(
func.sum(MyModel.MyColumn).label("mySum")
).filter_by(
MyValue=some_value
).first()
# Depending on the column datatype, it's either int:
print(result.mySum)
# Or if the data is decimal/float:
print(float(result.mySum))
与之前的回答相比,主要的区别在于:
以前是用:
query(func.sum())
而从0.6.5版本开始,语法变成了:
query.with_entities(func.sum())
http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.with_entities
22
我觉得你需要在“func”这个包里使用sum()这个函数:
from sqlalchemy import func
cursor = self.db.query(func.sum(Drive.wipe_end - Drive.wipe_start)).filter(Drive.package_id==package.package_id).filter(Drive.wipe_end!=None)
total = cursor.scalar()