sidewinder sidewinder - 1 month ago 6x
MySQL Question

SQL Alchemy - Getting a list of tables

I couldn't find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?

I used the class method to create the tables.


All of the tables are collected in the tables attribute of the sqlalchemy MetaData object. to just get a list of the names of those tables:

>>> metadata.tables.keys()
['posts', 'comments', 'users']

If you're using the declarative extension, then you probably aren't managing the metadata yourself. Fortunately, the metadata is still present on the baseclass,

>>> Base = sqlalchemy.ext.declarative.declarative_base()
>>> Base.metadata

If you are trying to figure out what tables are present in your database, even among the ones you haven't even told sqlalchemy about yet, then you can use table reflection. sqlalchemy will then inspect the database and update the metadata with all of the missing tables.

>>> metadata.reflect(engine)