Adding a CMS to Your Flask Web App Transcripts
Chapter: Appendix: Modeling data with SQLAlchemy classes
Lecture: SQLAlchemy model base class
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Νow we defined our package class we saw that it's not really going to work or at least I told you it's not going to work unless we have a base class.
0:08
So what we're going to to, is going to define another Python file here and this is going to seem a little bit silly
0:14
to have such small amount of code in its own file but it really helps break circular dependencies so totally worth it.
0:21
When I create a file here called model base. And you would think if we're going to create a class it would be something like this, SQLAlchemyBase.
0:29
Then we would do stuff here right? That's typically how you create a class. But it's not the only way and it's not the way that SQLAlchemy uses.
0:36
So what SQLAlchemy does is it uses a factory method to at run time, generate these base classes. We can have more than one. We can have a standard one.
0:46
We can have a analytics database one. All sorts of stuff. So you can have one of these base classes for each database you want to target.
0:55
And then factor out what classes go to what database based on like maybe the core database or analytics by driving from these different classes.
1:05
We don't need to do that. We're just going to have the one. But it's totally reasonable. So let's go over here and say
1:10
import sqlalchemy.ext.declarative as dec add something shorter than that. And then down here instead of saying the class
1:20
then we say the dec.declarative_base(). That's it, do a little clean up, and we are done. Here's our base class
1:27
and now we can associate that with a database connection and these classes. So we just come over here in the easiest way
1:34
and PyCharm is just to put it here and say Yes, you can import that at the top. So it adds that line rewrite there, and that's it.
1:43
This class is ready to be saved to the database. We have to configure SQLAlchemyBase itself a little bit more. But package, it's ready to roll.