I have a database for my website that is hosted on Heroku and uses Flask and Python. The model structure looks like:
class MyDataModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
property1 = db.Column(db.String(240), default = "")
property2 = db.Column(db.String(240), default = "")
property3 = db.Column(db.String(240), default = "")
When I try to update this model to something with an additional property (property4) shown below, the website doesn’t work. Is there a way to add an additional property to a model so that the model still functions properly?
class MyDataModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
property1 = db.Column(db.String(240), default = "")
property2 = db.Column(db.String(240), default = "")
property3 = db.Column(db.String(240), default = "")
property4 = db.Column(db.String(240), default = "")
The db is set up like:
db = SQLAlchemy()
app = Flask(__name__)
db.init_app(app)
2
Answers
SQLAlchemy allows you to automatically create the database structure based on your model. But this function does not update tables if they are already in the database. This is default SQLAlchemy behavior.
To update the table structure based on the model you need to do a migration using a migration library like Alembic. You can find instructions and detailed information on SQLAlchemy database migrations for Flask applications here:
https://flask-migrate.readthedocs.io/en/latest/
For the database migration in the
flask
, you need to set it up on your own.Create a
manage.py
file,To initiate the database, you need to run this command,
After you run the database initialization you will see a new folder called “migrations” in the project.
For migrations,
To apply in the database,
Since you are using Heroku the commands will be different in Heroku.
Reference