nonagon
nonagon

Reputation: 3483

dynamically creating a set of SQLAlchemy tables

I have a simple table defined with SQLAlchemy declarative:

Base = declarative_base()
class MyTable(Base):
    __tablename__ = 'mytable1'
    row_id = Column(INT, primary_key=True)
    another_column = Column(CHAR(10))

I'd like to create a set of tables, with these names:

table_names = ('mytable1', 'mytable2', 'mytable3', 'mytable4')

Is there a simple way to create this set of tables, all with the same column definitions (but each with its own name), without repeating the table definition?

Upvotes: 4

Views: 3538

Answers (1)

TheSoundDefense
TheSoundDefense

Reputation: 6945

A dictionary would be the best way to go here. Perhaps something like:

table_dict = {}
for i in range(4):   # Create
  table_name = "mytable" + str(i)
  table_dict[table_name] = MyTable(table_name)

for i in range(4):   # Query
  session.query(table_dict["mytable" + str(i)])

Something like that is probably what you're looking for. This would also let you create the dictionary keys automatically, like in a for loop.

EDIT: I assumed you were making instances of the MyTable class, but looking again that does not appear to be the case. I don't know the specifics of SQLAlchemy but my guess is you'll want to create MyTable instances using the __init__ function.

EDIT EDIT: if you want to create multiple table objects, you could create a function to generate and return a new class. Maybe something like this:

Base = declarative_base()

def TableCreator(tablename):
  class MyTable(Base):
    __tablename__ = tablename
    row_id = Column(INT, primary_key=True)
    another_column = Column(CHAR(10))
  return MyTable

Then you could call it with mytable1 = TableCreator("mytable1").

Upvotes: 7

Related Questions