On Wednesday, May 1, 2013 1:08:41 PM UTC-4, Michael Bayer wrote: > > > On May 1, 2013, at 12:58 PM, Michael Nachtigal < > [email protected] <javascript:>> wrote: > > > Hello, everyone, > > > > I have an existing database, and I'm trying to use reflection to > populate my metadata from an existing DB, but then define a declarative > class (based on one of the tables in the db), but a class with custom > "renamed" mapped attributes. > > See the code below for what I have now (which "works"), but is there a > better way to do what I'm trying to do using sqlalchemy? > > > > my_engine = create_engine(...) > > my_metadata = MetaData(bind=my_engine) > > Base = declarative_base(bind=my_engine, metadata=my_metadata) > > my_metadata.reflect() > > > > class User(Base): > > __tablename__ = 'user_table' > > > > # is there a way to access the User member variables here to rename > them? > > # I can't seem to access __table__ here to get at the mapped columns > > > > # at this point, the User class does have all of the necessary mapped > field names, but I want to rename them > > User.name = User.user_name > > User.location = User.address > > # ... and so on ... > > > > Feel free to ask for clarification or correct my choice of words, and > many thanks in advance for your time and reply! > > I'm not sure how that works exactly because __tablename__ will cause it to > produce a new Table object, attempting to replace the existing one in > my_metadata, and you'll get an error. > > Specifying a declared class from an existing table should use __table__ > (see > http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative). > > You can then map alternate names referring to that table object: > > user_table = my_metadata.tables['user_table'] > > class User(Base): > __table__ = user_table > > name = user_table.c.user_name > location = user_table.c.address > > Thank you for the quick reply! I double checked, and my original code does work, although I'm not sure how to tell if it works indistinguishably from your solution.
Follow-up question: In code like the following, is there any danger of multiply binding to my_engine and/or my_metadata? my_engine = create_engine(...) my_metadata = MetaData(bind=my_engine) Base = declarative_base(bind=my_engine, metadata=my_metadata) -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sqlalchemy?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
