首页 > 解决方案 > 使用sqlalchemy python查询表中的sum 2列

问题描述

我是使用 python3 的新手,我有桌面钱包:

ID name score1 score2
 1 name1    10     11
 2 name2     1      2
 3 name3     5      6

我如何查询结果:

total_score = score1 + score 2

ID name total_score
 1 name1         21
 2 name2          3
 3 name3         11

然后我尝试将 hybrid_method 添加到 Wallet 模型:

@hybrid_method
def total_score(self, fields):
    return sum(getattr(self, field) for field in fields)

@total_score.expression
def total_score(cls, fields):
    return sum(getattr(cls, field) for field in fields)

和 :

wallets = Wallet.total_score(['socre1', 'score2']).label('total_score')

但是钱包变量没有给出任何东西。我在中使用代码:SqlAlchemy(Postgres + Flask):如何对多列求和?

标签: pythonmysqlpython-3.xsqlalchemy

解决方案


推荐阅读