Paul1911
Paul1911

Reputation: 193

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

Upvotes: 1

Views: 227

Answers (1)

Andrew Eckart
Andrew Eckart

Reputation: 1726

Try this:

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

Upvotes: 1

Related Questions