How to add property to PostgreSQL database that is hosted on Heroku with Flask/Python?

Issue

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)

Solution

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/

Answered By – Gerballi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published