Python for Entrepreneurs Transcripts
Chapter: Course Conclusion
Lecture: Lightning review: sqlalchemy
0:01 We have a beautiful website but it does nothing because it has no database, there's nowhere to save our data so we said next up, sqlalchemy.
0:10 And the primary thing we do in sqlalchemy is map classes to tables and relationships between them.
0:17 So here's our album table, we have created this sqlalchemy base which all of our models derive from, we set the table name, the __tablename__ to album
0:26 to control what is in the database, and then we give it just columns. So, for each column we want the database, we create a field and we say
0:34 sqlalchemy.column, and we give it a type here the first one is an integer,
0:38 the second one is a string, the third and fourth integers and floats respectively. We also saw that we can do things like add a primary key
0:45 and make that auto incrementing or make something required and we even have a relationship here between the track table
0:52 of one to many relationship, and the albums. These models can have default values, which means when we insert them
0:59 they automatically get these fields initialized and these can be built in things, like here we have the now method,
1:05 you want to be very careful to not pass now () as the default because that will call now, and every model will basically have the time of app start
1:17 you want to pass the function, not the result of the function. So now without parentheses. We can also come up with more interesting ones,
1:24 where we write a lambda expression and do whatever it is that we like and really you could write any function
1:30 outside of this class and then pass it here as well. Without primary keys, databases basically don't work.
1:37 Primary keys are very important for uniqueness, they're important for relationships and things like that.
1:42 So we've seen in sqlalchemy that when we can say primary key = true magic happens, it just creates the index and registers the primary key,
1:49 all those kinds of things. If we're doing any sort of queries, it's very important to have an index.
1:56 Indexes can make the query results a hundred, maybe a thousand times faster and it's as simple as saying index = true on the field
2:04 so you certainly want to think about how you are going to query this data as you define the classes,
2:09 and maybe you need some sort of uniqueness constraint here's an account and we should not have two different accounts with the same email
2:17 so we're going to be able to both index this email, search by this email but also enforce in a uniqueness by just saying unique = true.