from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine Base = automap_base() # engine, suppose it has two tables 'user' and 'address' set up engine = create_engine("sqlite:///mydatabase.db") # reflect the tables Base.prepare(engine, reflect=True) # mapped classes are now created with names by default # matching that of the table name. User = Base.classes.user Address = Base.classes.address session = Session(engine) # rudimentary relationships are produced session.add(Address(email_address="email@example.com", user=User(name="foo"))) session.commit() # collection-based relationships are by default named # "
_collection" print (u1.address_collection)
Here is what the above code is Doing:
1. Create a new Engine instance.
2. Create a new MetaData instance.
3. Use the MetaData instance to generate a new Table object, representing the table named “user”.
4. Create a new mapper() instance, using the Table object as the argument.
5. Create a new class called “User”, which will be mapped to the “user” table.
6. Create a new Session instance.
7. Add a new User object to the session.
8. Commit the session.
9. Query the database for the first User object.
10. Print the User object’s name attribute.