Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: 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
Now for SQLAlchemy to work right
0:02
we need to put a base class here.
0:05
It needs to be a special one.
0:06
Every class that maps to the same database
0:10
needs to use the same base class.
0:13
You can have different ones, like if you have
0:15
an analytics database, and you have a core data database
0:19
those might be different classes
0:20
but all the ones that go into one database
0:22
they should be the same.
0:24
Okay, so how do we do that?
0:25
Well, we're going to define a class
0:27
and it's really quite simple.
0:28
You sort of create one and only one of them
0:31
from SQLAlchemy.
0:33
So I'm going to put that into its own separate file, now.
0:36
I think this one totally justifies its own file.
0:39
What I'm going to do here is pushing the limit
0:41
of maybe this is a little too fine grained
0:43
but there's only one and it's supposed to be shared.
0:45
So I think what I'm going to do is, do this.
0:51
Create a model base class and then we have to
0:55
import SQLAlchemy.extensions.declarative
1:01
I'll just say, shorts we don't have to say
1:02
too much there just, as dict then I'm going to
1:04
create a class called SQLAlchemyBase.
1:09
This class is the class that's going to be the base class
1:12
but instead of defining it this way
1:13
we use a factory method out of this place here
1:17
so we say, declarative_base like that.
1:23
And that's it.
1:24
This is now our base type.
1:26
It gets created at runtime by SQLAlchemy
1:28
and then, by virtue of deriving from it, it basically means
1:33
we're telling SQLAlchemy, "Here's another class that you're managing."
1:36
So for example, put that here and let PyCharm import it.
1:42
So for the top, we have from model base, import this
1:45
and those two lines are going to pretty much be the same
1:48
for all of our types.
1:49
And that's it, this class can now be loaded and saved
1:54
from the database once we connect to it.