1

Is there a way to define tables in the sqlalchemy declarative base in a programmatic manner? Let's say I have a table with many (thousands) of columns with sequential names, is there a way to define the columns with a for loop?

Going from something like this:

class MyTable(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True)
    column_1 = Column(Integer)
    column_2 = Column(Integer)
    column_3 = Column(Integer)
    column_4 = Column(Integer)
    column_5 = Column(Integer)
    column_6 = Column(Integer)

    def __init__(self, column_1, column_2, column_3, column_4, column_5, column_6):
        self.column_1 = column_1
        self.column_2 = column_2
        self.column_3 = column_3
        self.column_4 = column_4
        self.column_5 = column_5
        self.column_6 = column_6

to this:

class MyTable(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True)


    for i in range(7):
        # Define Columns
        pass 

    def __init__(self, data):
        for i in range(7):
            # set data
        pass 
João Almeida
  • 4,487
  • 2
  • 19
  • 35

0 Answers0