PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

SqlAlchemy (Postgres + Flask ):Bagaimana cara menjumlahkan banyak kolom?

Anda perlu membuat ekspresi untuk 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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Mengelola Database PostgreSQL Anda Dari ClusterControl CLI

  2. Menambahkan batasan satu-dari-dua bukan nol di postgresql

  3. cap waktu postgresql ke nilai std::chrono

  4. setParameter() tidak menyetel tanda kutip yang tepat

  5. Gambaran Umum Replikasi Logis di PostgreSQL