sql - How to automatically reflect table relationships in SQLAlchemy or SqlSoup ORM? -
how tell sqlalchemy automatically reflect basic foreign key references references other orm objects , not integer fields?
in both sqlalchemy , it's sqlsoup, table columns reflected automatically , relations can defined manually:
class user(base): __table__ = metadata.tables['users'] loan = relation(loans)
...
you can define relationships on sqlsoup classes: >>> db.users.relate('loans', db.loans)
try magic ) works simple fk relations, , without db schemes
from sqlalchemy import create_engine, metadata sqlalchemy.orm import mapper, relation engine = create_engine("sqlite://", echo=true) engine.execute(''' create table foo ( id integer not null primary key, x integer )''') engine.execute(''' create table bar ( id integer not null primary key, foo_id integer, foreign key(foo_id) references foo(id) )''') metadata = metadata() metadata.reflect(bind=engine) mappers = { } repr_name = lambda t: '%s%s' % (t[0].upper(), t[1:]) table in metadata.tables: cls = none # 1. create class object cls_name = repr_name(str(table)) exec("""class %s(object): pass""" % cls_name) exec("""cls = %s""" % cls_name) # 2. collect relations fk properties = {} c in metadata.tables[table].columns: fk in c.foreign_keys: name = str(fk.column).split('.')[0] properties.update({ name: relation(lambda: mappers[repr_name(name)]), }) # 3. map table class object mapper(cls, metadata.tables[table], properties=properties) mappers.update({cls_name: cls}) if __name__ == '__main__': sqlalchemy.orm import sessionmaker print 'mappers: ' m in mappers.values(): print m session = sessionmaker(bind=engine)() foo = foo() foo.x = 1 session.add(foo) session.commit() print session.query(foo).all() bar = bar() bar.foo = foo session.add(bar) session.commit() print session.query(bar).all()
Comments
Post a Comment