shnap
shnap

Reputation: 185

Adding multiple columns in a table such as using a for / while loop in flask-sqlalchemy

I want to create a child table using Flask-SQLAlchemy that holds around 600 columns.
Each column is supposed to be a different hobby with a boolean value of true or false (whether or not he has this hobby).
However I do have an issue. Using Flask-SQLAlchemy's Model to create it seems problematic since I will have to write each field myself.
i.e:

class hobbies(database.Model):
   id = db.Column(db.Integer, primary_key=True)
   user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
   hobby1 = db.Column(db.Boolean)
   hobby2 = db.Column(db.Boolean)
   hobby3 = db.Column(db.Boolean)
   ....
   ....
   hobby600 = db.Column(db.Boolean)

(database stands for the variable that holds - database = SQLAlchemy(app))

Is there a way such as using a for or a while loop to add all of the columns to the table?

Thank you for your time.

Upvotes: 0

Views: 406

Answers (1)

faris404
faris404

Reputation: 373

This is bad table design(no offence), instead of this you can create table as given below

class Hobbies(database.Model):
   id = db.Column(db.Integer, primary_key=True)
   hobby = db.Column(db.String(50))

class UserHobbies(database.Model):
   user_id = db.Column(db.Integer, db.ForeignKey('user.id'),primary_key=True)
   hobbie_id = db.Column(db.Integer, db.ForeignKey('hobbies.id'),primary_key=True)

Instead of creating 600 columns in hobbies table just create 600 rows and create another table UserHobbies for many to many relationship with users and hobbies.
You can also utilize bulk_insert_mappings(ModelName,list_data) function for inserting bulk data in to hobbies table.

Upvotes: 3

Related Questions