Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Database migrations with Alembic
Lecture: Concept: auto-generating changes
Login or purchase this course to watch this video and the rest of the course contents.
0:00 The best way to use a Alembic I think is to let SQLAlchemy at least pre-build the various revision changes for you
0:09 and then you can edit them still if you like. In order to do that, you have to edit the env.py file, and you have to set
0:16 the target metadata to the SQLAlchemyBase.metadata and just like before, it is super important that that SQLAlchemyBase thing
0:24 sees all of your various models. That means you have to do some form of import like this from pypi.data import *
0:33 or something to that effect, to make sure that everything is loaded up. But adding these two things will connect
0:39 SQLAlchemy and Alembic so that Alembic can use your models to generate revisions and that is way, way sweeter.
0:48 So just simply setting this target metadata is all we have to do to connect our ORM models to Alembic. And then to make a change, we just add
0:56 the auto generate, like we had before but now we say auto generate this change. It's going to go detect the various changes
1:04 and then it's going to create another one of these files. We open up that file and now it's better. We have this little section in upgrade.
1:11 Instead of pass, it says these were auto generated by Alembic, please review them and if you're happy just leave them or if you need to, make changes.
1:22 Nothing happens when you auto generate this but it generates the file as it can guess and then you edit it to do what it needs.
1:29 Finally, you just apply it again and it's going to apply that auto generated revision change, rather than the one
1:36 you had to manually write, and that's Alembic. A very nice way to keep evolving your database structure, along with
1:44 the evolution of your SQLAlchemy models and for the most part making that automatic.