4

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?

2
  • You should not make variable names out of data, especially important data. You should be storing these tables in a dictionary. Commented Aug 10, 2014 at 3:43
  • @TheSoundDefense, I'm not sure I follow - I rehprased the question to make it more clear that I'm just looking for a way to define a set of tables with different names but the same column definitions Commented Aug 10, 2014 at 15:01

1 Answer 1

7

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").

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the confusion - I was indeed looking for a way to define these tables using SQLAlchemy. I'm new to it, and I couldn't see a simple way to do this. I edited the question to make this more clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.