2016-05-19 6 views
0

は、私はSQLAlchemyのモデルを持っている、のは、言ってみましょうSQLAlchemyモデルのアドホック計算列を作成する方法は?</p> <pre><code>class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) password = Column(String) </code></pre> <p>そして、私は、クエリを持っている:

session.query(User, (User.frist_name + ' ' + User.last_name).label('full_name')).all() 

それは私に[(User(...), 'John Smith'), ...]のような出力を与えるだろう。

私が達成したいのは、SQLAlchemyをfull_nameUser()オブジェクトをワンショットクエリの属性として添付することです。これには最高のレシピは何ですか?

答えて

0

あなたのUserモデルに各INSERT/UPDATEの列full_nameを計算するためのトリガーを持つことができます。私はhybrid_propertyを使用することをお勧めしますが。

あなたのUserモデルでは、このようなことがあります。

@hybrid_property 
def full_name(self): 
    # This is used for calculating the full name in python side. 
    return '{0} {1}'.format(self.first_name, self.last_name) 

@full_name.expression 
def full_name(cls): 
    # This is an expression that gets executed as SQL. 
    return cls.first_name.concat(' ').concat(cls.last_name) 
関連する問題

 関連する問題