返回连接的两个SqlAlchemy列

时间:2014-04-15 01:48:32

标签: python sqlalchemy flask-sqlalchemy

我正在使用FlaskSQLAlchemy。我有一个Person模型,我想要一个返回Person全名(第一个+最后一个)的属性。

我尝试使用@declared_attr,但输出:

"person.first_name || :param_1 || person.last_name"

这是我的代码:

class Person(Base):
    __tablename__ = 'person'

    id = Column(Integer, primary_key = True)
    type = Column(String(50))
    first_name = Column(String(120), index = True)
    last_name = Column(String(120), index = True)

    @declared_attr
    def name(cls):
        "Returns Person's full name."
        return cls.first_name + ' ' + cls.last_name

2 个答案:

答案 0 :(得分:4)

@davidism建议使用混合扩展,而我说,为什么不使用SQLAlchemy' column_property function

示例:

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    firstname = Column(String(50))
    lastname = Column(String(50))
    fullname = column_property(firstname + " " + lastname)

答案 1 :(得分:3)

使用hybrid扩展程序:

from sqlalchemy.ext.hybrid import hybrid_property

class Person(Base):
    # ...
    @hybrid_property
    def name(self):
        return '{0} {1}'.format(self.first_name, self.last_name)

    @name.setter
    def name(self, value):
        self.first_name, self.last_name = value.split(' ', 1)

    @name.expression
    def name(cls):
        return db.func.concat(cls.first_name, ' ', cls.last_name)