Create tables with many attributes in SQLite via Python - best way?

for a project, I have to create a table with 51 attributes in SQLite via Python using ORM, so defining the tables as classes. Structure is like this table, but with y1-y50, which are similar.

class Train(Base):
    __tablename__ = 'train'
    #Name columns and attributes
    x = db.Column(db.Float, primary_key = True, nullable = False)
    y1 = db.Column(db.Float)
    y2 = db.Column(db.Float)
    y3 = db.Column(db.Float)
    y4 = db.Column(db.Float)

I could now just copy those yi variables, paste and adjust them. But is there a better way to do so? Should I define the variables by help of a for i in range() loop? What is the best way to approach this?

Thank you already! Paul

1 answer

  • answered 2021-05-03 17:54 Andrew Eckart

    Try this:

    for i in range(50):
        setattr(Train, f"y{i+1}", db.Column(db.Float))