[英]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. 我有一个带有列item_id
的类Score
和几个具有不同分数类型(score1,score2,score3 ...)的字段,它们都具有整数值。
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. 我需要编写一个查询,获取分数类型列表,并返回一个列表,其中包含具有itemid
和列表中提到的所有分数类型的分数总和的对象。 I'm trying to do this using hybrid method but confused about how to write the query. 我正在尝试使用混合方法来执行此操作,但是对于如何编写查询感到困惑。
model.py 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 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
您需要为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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.