Let's say we wanted to add some new data to the Books model, such as a new column for the price of the book, but we can't just drop_all and create_all because now there's users relying on the database being available. If we recreated the database, we would have to go back and insert all of the data again. If there was any user generated data, we would lose it.

We could just go into pgAdmin and issue some SQL, but there's a better way to do it in Python and keep track of the changes.

This is what database migrations are for.

Using the Alembic library, we can auto-generate SQA code to transform the database from the old version into the new version. Each time a migration is performed, a script is created with details on how to convert the database to the new version (upgrade) and how to reverse the migration to the old version (downgrade).

The version of the models is tracked by a new table, called alembic_version , which is automatically created by Alembic in your database.

Essentially, this is how Alembic works with your models and database:

You change a model in models.py

You ask Alembic what's different about the models

Alembic creates a .py script to convert the models to the current definition

script to convert the models to the current definition You tell Alembic to proceed with the upgrade

Tables are changed and the current version is stored in the alembic_version table in Postgres