Python-powered chat apps with Twilio and SendGrid Transcripts
Chapter: Using our database with the SQLAlchemy ORM
Lecture: Concept: SQLAlchemy model class
Login or purchase this course to watch this video and the rest of the course contents.
0:00 To work with our database. We did very little direct database operations. What instead we did is we said we're going to use an
0:07 ORM, an object relational mapper named SQLAlchemy. And over there we create classes and then SQLAlchemy will manage the tables and the
0:16 inserts and the queries and everything like that for us. Do we get started by giving a short name to the SQLAlchemy Name Space and
0:23 We Create a Class which derived from SQLAchemy Base, which we created elsewhere. Give it a table name so that,
0:30 SQLAlchemy knows where to store it in the database. And then we start defining the columns as fields in this class.
0:37 So we define ID, which is an sa column of type sa string It's a primary key, and it's auto incrementing. So when we do an insert,
0:45 it automatically gets the correct and latest value. We don't have to worry about that. It's also really good to know when these things were created.
0:53 When did this user sign up? When was their order placed? We're going to have a creative date,
0:58 which is a datetime column, but we gave it a default value of datetime.daytime.now a function not the result of calling that function.
1:06 Remember, no parentheses there. And what happens is whenever you insert something
1:11 SQLAlchemy will automatically call that function and set the creative date right when you did this you don't have to do either of these things.
1:17 They're automatic as you save the data. We want to give the user a name like Michael. I want to give them a phone number like WhatsApp :+1503,
1:27 Whatever it is. And because we may want to query by their phone number. We're gonna put an index here,
1:33 Same thing for their email, but as a string and give it an index. We also have orders and users and their related to each other.
1:41 So we created this relationship. There's a relationship over to the order class Over there There's a user field which gets back populated,
1:48 and here we have a list of orders a one to many relationship from user to their orders, right here. And this allows us to quickly given a user,
1:58 go find their orders or given an order,step back and find the user its associated with.