Full Web Apps with FastAPI Transcripts
Chapter: Course conclusion and review
Lecture: SQLAlchemy models
0:00 The next major area we focused on was to actually start saving all of this data
0:04 to the database. Remember, we had taken the top 100 packages,
0:08 and once we were able to save stuff to the database,
0:10 we imported those there. We started having our users actually saved in the database when
0:15 they registered and then validated from the database when they logged in and so on.
0:19 So a couple of things that we did there for those models was we created this
0:22 declarative_base. So
0:24 sqlalchemy, extensions, declarative, declarative_base.
0:27 And this is really just a class,
0:29 as if you type the word class space something,
0:31 but it's more dynamically generated. And the idea is: Everything that derives from this class
0:37 will be a table that is managed by SQLAlchemy.
0:41 You have Package, Release and User because they all three derived from this particular instance
0:46 of this base class, this particular type we created here.
0:50 It means that when we go to that base class and say,
0:53 create all your tables or you have relationships or things like that,
0:57 all those tables are gonna be related and created through that one action.
1:01 And it's all this base class, the SqlAlchemyBase class, that makes that happen.
1:05 And then, for each one of these classes, in this case Package,
1:08 we're going to do a couple of things.
1:10 We define a dunder table name and then we're gonna give it some columns
1:14 that are also fields in our classes,
1:15 so an id, in this case
1:17 we're gonna say this is an integer,
1:18 it's autoincrementing, and it's a primary key,
1:21 so we don't have to set it,
1:22 just as we insert stuff in the database,
1:24 it will automatically get this primary key set appropriately and uniquely from the database.
1:29 Then we'll have a summary, which is a string, a size
1:31 which is an integer, a home_page,
1:33 which is a string. We even saw we can set up really cool relationships like
1:37 for example, this package has a bunch of releases.
1:40 So instead of doing additional database queries manually,
1:43 we're just gonna set up the relationship.
1:45 And if we interact with the releases collection,
1:48 it's automatically going to get that from the database,
1:50 either because we've done a join ahead of time knowing that's gonna happen or through a
1:54 lazy loading thing, and it'll go back to the database and get that data if we need it.