Search code examples
pythonmysqlflask-sqlalchemytablecolumn

Flask + SqlAlchemy ALTER table


I'm developing a web application based on Flask + SqlAlchemy + MySQL and I followed that answer. I have to change my model so I need to alter the db table adding a column, but I don't want to lose the stored data dropping and recreating it.

I read something about Flask-Migrate and Alembic... are they essential to solve my problem? What can I do?


Solution

  • Yes, they can be helpful. I would suggest Alembic (http://alembic.readthedocs.org/en/latest/) which is from the author of SQLAlchemy.

    With migration you need to define the changes you want to make. In your case, you want to add a column. I don't think it would be a problem. Adding columns usually don't cause data loss. Changing type or deleting a column causes data loss.

    You can of course directly update the table too, just update your models to reflect the new column. But migrations are usually more manageable ways of doing it.