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