简体   繁体   中英

SqlAlchemy (Postgres + Flask ) : How to sum multiple columns?

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

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

Obviously this does not work. Could you please help me write the query, much thanks!

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}, ...]

You need to create expression for 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM