Python for .NET Developers Transcripts
Chapter: Database access and ORMs in Python
Lecture: Concept: Defining entities

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's review how we created our various entities our classes that then were mapped over to database tables
0:07 and actually were used to even create those tables. In SQLAlchemy, everything happens in that world
0:13 for entities by deriving from this declarative base class that is generated, not with the class keyword but as a runtime object.
0:22 So that's easy to do in Python and that's how they do it in SQLAlchemy. So we just say sqlalchemy.ext.declarative.declarative_base.
0:30 This creates the type and you can give it whatever name you want. I like the name SQLAlchemyBase, since it represents a type.
0:37 I give it this camel case type of naming convention. Name it whatever you want. It doesn't actually have anything to do with anything
0:42 just this object is the base class and you need to inherit from it. So this is a singleton, you get one and only one of them.
0:50 So make sure you don't create two. And then to create new classes, like a Guitar or User we just derive from SQLAlchemyBase.
0:58 Then what we have to do is fill out this guitar class for example. So it derives from SQLAlchemyBase, as we just saw
1:04 and then we have these static fields which represent the columns. So we have an ID, a name, an image, a style, and a price.
1:11 We set these to be all SQLAlchemy columns and then you specify the type like a sqlalchemy.integer, or string, or float or whatever you want.
1:19 And then we can optionally set other values like the ID's going to be a primary key and it's going to auto-increment in the database
1:25 so we don't have to worry about that. That's cool. We're going to query by style and filter by price so we want index there. So we say index=True.
1:33 You can also do relationships but we only have one table in our example so we're not really going to get into setting up relationships
1:39 but they're pretty easy to do here, as well.

Talk Python's Mastodon Michael Kennedy's Mastodon