使用反射在类定义之后分配column_property

时间:2015-03-29 14:46:53

标签: python reflection sqlalchemy

我现有数据库 test.db ,表格用户。表用户

的转储
BEGIN TRANSACTION;
CREATE TABLE users (
    id INTEGER NOT NULL, 
    firstname VARCHAR, 
    lastname VARCHAR, 
    PRIMARY KEY (id)
);
INSERT INTO "users" VALUES(1,'Alex','Black');
COMMIT;

我正在尝试在用户类定义后分配 column_property ,但当我使用 DeferredReflecton 作为mixin类时,此方法不起作用:

from sqlalchemy import create_engine, Table, Column
from sqlalchemy.orm import sessionmaker, column_property
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection

Base = declarative_base(cls=DeferredReflection)
Session = sessionmaker()

class User(Base):
    __table__ = Table('users', Base.metadata,
        Column('firstname'),
        Column('lastname'))

User.fullname = column_property(User.__table__.c.firstname + ' ' + User.__table__.c.lastname)

def main():
    engine = create_engine('sqlite:///test.db')
    Base.prepare(engine)
    session = Session(bind=engine)
    user = session.query(User).filter_by(id=1).one()
    print 'fullname:', user.fullname

if __name__ == '__main__':
    main()

输出:

fullname: Traceback (most recent call last):
  File "satest.py", line 39, in <module>
    main()
  File "satest.py", line 35, in main
    print 'fullname:', user.fullname
  File "/home/xndr/.playground/sqlalchemy/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 259, in __str__
    return str(self.parent.class_.__name__) + "." + self.key
AttributeError: 'ColumnProperty' object has no attribute 'parent'

0 个答案:

没有答案