SqlAlchemy(Postgres + Flask):如何对多列进行求和?

时间:2016-02-28 15:16:26

标签: python postgresql sqlalchemy flask-sqlalchemy

我有一个Score课,其中item_id列有几个不同分数类型(score1,score2,score3 ...)的字段都有整数值。

我需要编写一个获取分数类型列表的查询,并返回一个列表,其中包含itemid的对象,以及列表中提到的所有分数类型的分数总和。我正在尝试使用混合方法,但对如何编写查询感到困惑。

model.py

class Score(db.Model):

    __tablename__ = 'scores'

    item_id                     = db.Column(db.Integer(), primary_key=True)
    score1                      = db.Column(db.Integer(), nullable=False)
    score2                      = db.Column(db.Integer(), nullable=False)
    score3                      = db.Column(db.Integer(), nullable=False)
    score4                      = db.Column(db.Integer(), nullable=False)

    @hybrid_method
    def total_score(self, fields):
        ts = 0
        for field in fields : 
            ts = ts + self[field]
        return ts

controller.py

app.route('/scores', methods=['POST'])
def scores():
    fields = ['score1', 'score2']
    scores = Score.query.all().order_by('total_score')

显然这不起作用。你能帮我写一下这个问题,非常感谢!

这就是我需要获得最终输出的方式:

[{'item_id' : 'x1', 'total_score' : y1},{'item_id' : 'x2', 'total_score' : y2},{'item_id' : 'x3', 'total_score' : y3}, ...]

1 个答案:

答案 0 :(得分:1)

您需要为hybrid_method

创建expression
class Score(db.Model):
    __tablename__ = 'scores'
    item_id  = db.Column(db.Integer(), primary_key=True)
    score1 = db.Column(db.Integer(), nullable=False)
    score2 = db.Column(db.Integer(), nullable=False)
    score3 = db.Column(db.Integer(), nullable=False)
    score4 = db.Column(db.Integer(), nullable=False)

    @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)


fields = ['score1', 'score2']
scores = db.session.query(Score.item_id, Score.total_score(fields).label('total_score')).order_by('total_score')
final_output = [score._asdict() for score in scores]