jim jarnac
jim jarnac

Reputation: 5152

Sqlalchemy - Auto-instantiate all tables

Here a simple sqlalchemy task, where i try to create instances of each table present in the database:

from sqlalchemy import MetaData, create_engine, Table
engine = create_engine("here my engine details...")
metadata = MetaData()

If i type engine.table_names() , I can see all my tables' names, for instance ['indicators', 'prices', 'scripts'].

I would normally go at creating instances of each of them as follow:

scripts = Table('scripts', metadata, autoload = True, autoload_with=engine)
indicators = Table('indicators', metadata, autoload = True, autoload_with=engine)
prices = Table('prices', metadata, autoload = True, autoload_with=engine)

But is there a way to create the Table instances without coding them explicitely?

Doing this:

tables = engine.table_names()
for table in tables:
    table = Table( table , metadata, autoload = True, autoload_with=engine)

obviously doesn't work. Any suggestion appreciated

Upvotes: 1

Views: 211

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169284

You can do just that. This code will get you a list of tables:

my_tables = [Table(table,metadata,autoload=True,autoload_with=engine) for 
             table in engine.table_names()]

If you prefer a dictionary do this:

my_tables = {table:Table(table,metadata,autoload=True,autoload_with=engine) 
             for table in engine.table_names()}

With the dictionary you get O(1) lookup of tables when accessing the elements of your dictionary:

my_tables['indicators']

Upvotes: 4

Related Questions