Adding a CMS to Your Pyramid 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 Now for SQLAlchemy to work right we need to put a base class here. It needs to be a special one. Every class that maps to the same database
0:11 needs to use the same base class. You can have different ones, like if you have an analytics database, and you have a core data database
0:20 those might be different classes but all the ones that go into one database they should be the same. Okay, so how do we do that?
0:26 Well, we're going to define a class and it's really quite simple. You sort of create one and only one of them from SQLAlchemy.
0:34 So I'm going to put that into its own separate file, now. I think this one totally justifies its own file.
0:40 What I'm going to do here is pushing the limit of maybe this is a little too fine grained but there's only one and it's supposed to be shared.
0:46 So I think what I'm going to do is, do this. Create a model base class and then we have to import SQLAlchemy.extensions.declarative
1:02 I'll just say, shorts we don't have to say too much there just, as dict then I'm going to create a class called SQLAlchemyBase.
1:10 This class is the class that's going to be the base class but instead of defining it this way we use a factory method out of this place here
1:18 so we say, declarative_base like that. And that's it. This is now our base type. It gets created at runtime by SQLAlchemy
1:29 and then, by virtue of deriving from it, it basically means we're telling SQLAlchemy, "Here's another class that you're managing."
1:37 So for example, put that here and let PyCharm import it. So for the top, we have from model base, import this
1:46 and those two lines are going to pretty much be the same for all of our types. And that's it, this class can now be loaded and saved
1:55 from the database once we connect to it.


Talk Python's Mastodon Michael Kennedy's Mastodon