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)
CodePudding user response:
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/
CodePudding user response:
For the database migration in the flask
, you need to set it up on your own.
Create a manage.py
file,
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
To initiate the database, you need to run this command,
$ python manage.py db init
After you run the database initialization you will see a new folder called “migrations” in the project.
For migrations,
$ python manage.py db migrate
To apply in the database,
$ python manage.py db upgrade
Since you are using Heroku the commands will be different in Heroku.