Python for Entrepreneurs Transcripts
Chapter: Course Conclusion
Lecture: Lightning review: sqlalchemy

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