SqlAlchemy(Postgres + Flask):如何求和多列? [英] SqlAlchemy (Postgres + Flask ) : How to sum multiple columns?

查看:132
本文介绍了SqlAlchemy(Postgres + Flask):如何求和多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class Score with a column item_id and several fields having different scores types(score1, score2, score3...)all having integer values.

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

I need to write a query that takes the list of scores types and returns a list with objects having itemid and sum of the scores of all score types mentioned in the list alongside. I'm trying to do this using hybrid method but confused about how to write the query.

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

显然不起作用。

这是我需要的最终输出:

This is how I need to have the final output :

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


推荐答案

您需要创建表达式,用于 hybrid_method

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]

这篇关于SqlAlchemy(Postgres + Flask):如何求和多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆