0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have a related question regarding many to many relationship like your solution. If I have a similar thing I want to save per person as well as compare between users for example if they like basketball, soccer and hockey (3 Boolean collumns). Is it better to make a many to many relationship like your solution or since it's only 3 fields I can just add them as columns in the user's table?
From my research the more standard ways is creating many to many relationship.But in this case I prefer creating three columns for each hobbies like you since its only three fields.

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.