4

I have a flask SqlAclchemy table called User:

class User(db.Model):
    id = db.Column(db.INTEGER, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)

i have now edited it and added this line;favCol = db.Column(db.String(12))

how do i update the table for it to recognize this new colum when i add a new user? At the moment when i create a User like User(username="bob",favCol="red") it gives me an error:

TypeError: 'favCol' is an invalid keyword argument for User

I have heard of solution with Migrate although i would prefer re a simpler solution if possible

SuperShoot
  • 9,880
  • 2
  • 38
  • 55
Conor Jalen
  • 61
  • 2
  • 8
  • Have you looked in the docs? They may have info there – Constantine Westerink Mar 21 '21 at 20:45
  • Yea, i did not find anything. I also tried : ```db.update(User)``` in the python console – Conor Jalen Mar 21 '21 at 20:54
  • You wouldn't get the `invalid keyword argument for ...` error if you've added the `favCol = db.Column(...)` declaration to your model correctly. You should expect to get a `sqlalchemy.exc.OperationalError` error when sqlalchemy tries to write to the table and the column doesn't exist yet in the database. – SuperShoot Mar 21 '21 at 20:59
  • You're unlikely to get answers with any better info than these: https://stackoverflow.com/questions/7300948/add-column-to-sqlalchemy-table – SuperShoot Mar 21 '21 at 21:03
  • Can i go to slite in the console and do something like : ALTER... – Conor Jalen Mar 23 '21 at 01:56

2 Answers2

1

If you don't care about the data in the database getting erased. You can do the following:

from terminal if 'py' doesn't start python, try 'python'. press enter after each of these commands

py
from projectdirectory import db
db.drop_all()
db.create_all()

If you care about your existing data, you need to use something like flask_migrate which uses alembic in order to help you do database migrations while maintaining your data.

Andrew Clark
  • 850
  • 7
  • 13
  • 2
    Is there any solution without having my data erased? – Conor Jalen Mar 24 '21 at 02:54
  • Yes. refer to the last paragraph of my submitted answer. It's not a simple solution though. It's too complex to explain in a few lines here on how you could implement it. You'll have to research flask_migrate for yourself. – Andrew Clark Mar 25 '21 at 02:11
0

This answer will help:
https://stackoverflow.com/a/17243132/19280304

For flask-SQLAlchemy, add this before the code

from flask_sqlalchemy import SQLAlchemy
engine  = SQLAlchemy(app).engine