0

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
  • What is db.Model? Are you using database migrations? How do you add the property to your local database? Commented Oct 24, 2022 at 13:40
  • What is the error you get? Commented Oct 31, 2022 at 6:07

2 Answers 2

4
+50

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/

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

Comments

1

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.

Reference

Comments

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.