Python for the .NET developer 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
0:03 our classes that then were mapped over to database tables
0:06 and actually were used to even create those tables.
0:09 In SQLAlchemy, everything happens in that world
0:12 for entities by deriving from this declarative base class
0:16 that is generated, not with the class keyword
0:18 but as a runtime object.
0:21 So that's easy to do in Python
0:23 and that's how they do it in SQLAlchemy.
0:24 So we just say sqlalchemy.ext.declarative.declarative_base.
0:29 This creates the type
0:30 and you can give it whatever name you want.
0:32 I like the name SQLAlchemyBase, since it represents a type.
0:36 I give it this camel case type of naming convention.
0:39 Name it whatever you want.
0:40 It doesn't actually have anything to do with anything
0:41 just this object is the base class
0:44 and you need to inherit from it.
0:46 So this is a singleton, you get one and only one of them.
0:49 So make sure you don't create two.
0:50 And then to create new classes, like a Guitar or User
0:54 we just derive from SQLAlchemyBase.
0:57 Then what we have to do is fill out this guitar class
1:00 for example.
1:01 So it derives from SQLAlchemyBase, as we just saw
1:03 and then we have these static fields
1:06 which represent the columns.
1:07 So we have an ID, a name, an image, a style, and a price.
1:10 We set these to be all SQLAlchemy columns
1:13 and then you specify the type
1:14 like a sqlalchemy.integer, or string, or float
1:17 or whatever you want.
1:18 And then we can optionally set other values
1:20 like the ID's going to be a primary key
1:22 and it's going to auto-increment in the database
1:24 so we don't have to worry about that. That's cool.
1:26 We're going to query by style and filter by price
1:29 so we want index there. So we say index=True.
1:32 You can also do relationships
1:34 but we only have one table in our example
1:36 so we're not really going to get into setting up relationships
1:38 but they're pretty easy to do here, as well.