式を作成する必要があります
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]