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 
5
  • 2
    A couple of answers that are probably related: stackoverflow.com/a/2768880/6560549, stackoverflow.com/a/38575915/6560549 Commented Aug 9, 2019 at 8:49
  • 1
    A table with columns with sequential names sounds a bit antipatternish. Commented Aug 9, 2019 at 9:35
  • @IljaEverilä I agree, this is to store spectroscopy data, each column corresponds to a wavelength, maybe I shouldn't be using a relational DB for this... Commented Aug 9, 2019 at 9:45
  • That, or use one that supports array / document types, or store something akin to (measurement_id, wavelength, value). Commented Aug 9, 2019 at 10:43
  • 1
    @SuperShoot thanks a lot, I ended up using the idea from the first answer you linked to. Commented Aug 9, 2019 at 11:45

0

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.