Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Modeling data with SQLAlchemy classes
Lecture: SQLAlchemy model base class
0:00 Νow we defined our package class
0:01 we saw that it's not really going to work
0:03 or at least I told you it's not going to work
0:05 unless we have a base class.
0:07 So what we're going to to, is going to define
0:09 another Python file here
0:10 and this is going to seem a little bit silly
0:13 to have such small amount of code in its own file
0:16 but it really helps break circular dependencies
0:19 so totally worth it.
0:20 When I create a file here called model base.
0:22 And you would think if we're going to create a class
0:25 it would be something like this, SQLAlchemyBase.
0:28 Then we would do stuff here right?
0:30 That's typically how you create a class.
0:31 But it's not the only way
0:33 and it's not the way that SQLAlchemy uses.
0:35 So what SQLAlchemy does is it uses a factory method
0:39 to at run time, generate these base classes.
0:41 We can have more than one.
0:43 We can have a standard one.
0:45 We can have a analytics database one.
0:49 All sorts of stuff.
0:50 So you can have one of these base classes for each
0:53 database you want to target.
0:54 And then factor out what classes go to what database
0:59 based on like maybe the core database
1:02 or analytics by driving from these different classes.
1:04 We don't need to do that. We're just going to have the one.
1:06 But it's totally reasonable.
1:08 So let's go over here and say
1:09 import sqlalchemy.ext.declarative as dec
1:14 add something shorter than that.
1:16 And then down here
1:18 instead of saying the class
1:19 then we say the dec.declarative_base().
1:22 That's it, do a little clean up, and we are done.
1:25 Here's our base class
1:26 and now we can associate that with a database connection
1:30 and these classes.
1:32 So we just come over here in the easiest way
1:33 and PyCharm is just to put it here and say
1:36 Yes, you can import that at the top.
1:38 So it adds that line rewrite there, and that's it.
1:42 This class is ready to be saved to the database.
1:45 We have to configure SQLAlchemyBase itself
1:48 a little bit more.
1:49 But package, it's ready to roll.