Search code examples
pythondatabaseflasksqlalchemyflask-sqlalchemy

SQLAlchemy: How can I update the table in the database when I update the model in models.py


I have as SQLAlchemy model called User and I want to add another property to the class, ex: address.

I tried adding a new class property, and hoped that SQLAlchemy would realize there is a change in the class and would update the table automatically. That is not case.

I've looked online on how to make changes to the model which would then update the table automatically, but all I have found is db.sessions where they manually type out the changes they want to make. Is there a better way to update a model?

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    # new class property that I want to add
    address = db.Column(db.String(100), nullable=False)

Solution

  • This is a great example of why database migrations are important. Ideally, all of your data definition should be done using migrations.

    Since you're already using Flask-SQLAlchemy, Flask-Migrate is probably a good fit:

    1. Add Flask-Migrate to your project's dependencies.

    2. Run flask db init to initialize migrations for your project (this is a one-time task).

    3. Update your model (it sounds like you've already done this).

    4. Run flask db migrate to generate a migration file (this should be done only as part of developing migrations).

      Review and, if necessary, edit the generated migration files to ensure that they capture the necessary changes. These files should be committed to your repository.

    5. Apply it with flask db upgrade (this will need to be done on each copy of the database when the new code is merged, i.e. on each development machine, in staging, in production, etc.)