sql >> Databasteknik >  >> RDS >> PostgreSQL

SqlAlchemy (Postgres + Flask ):Hur summerar man flera kolumner?

Du måste skapa uttryck för 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. förberedda uttalanden med psycopg

  2. mariadb Regexp någon gång returnera tom i lagrad procedur

  3. Biblioteket är inte laddat:/usr/local/opt/readline/lib/libreadline.6.2.dylib

  4. hur man optimerar den här frågan (4 mm tabeller involverade)