dimanche 29 mars 2015

Assign column_property after class definition with reflection

I have existing database test.db with table users. Dump of table users:



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


I'm trying assign column_property after User class definition, but when I use DeferredReflecton as mixin class this method don't work:



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()


Output:



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'





Aucun commentaire:

Enregistrer un commentaire