sql >> Database teknologi >  >> RDS >> PostgreSQL

SqlAlchemy (Postgres + Flask):Hvordan summerer man flere kolonner?

Du skal oprette udtryk 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]



  1. Betyder udvikling af kontaktoplysninger at ændre din database?

  2. Jokertegn i Java PreparedStatements

  3. Fra Stored Procedure returnerer du OUT parameter &OUT cursor &parse resultat (Oracle)

  4. Ansible elsker PostgreSQL