Python for Entrepreneurs Transcripts
Chapter: Accessing databases from Python: SQLAlchemy ORM
Lecture: Concept: Adding new data

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Finally let's talk about inserting data.
0:03 We've seen the unit of work in action with this session
0:07 and inserting objects are no different.
0:09 So again, we are going to use a session factory to create a session
0:11 and then to insert new objects, we just create new instances
0:14 at the types that map to those particular tables.
0:17 So if we want to create a new album, we just create a new album,
0:20 and we are going to set some properties.
0:22 In the example you saw me write the code,
0:24 I actually use name value keyword arguments to set the name
0:28 and the year in the album initializer.
0:31 But, you could just as well create them and sat them like this in an operative way
0:35 and that would be totally fine.
0:37 This is not yet putting the database, we are still going to have to add it to the session,
0:40 we also want to associate some tracks with this album,
0:42 so we are going to create a new track.
0:45 And we can actually go bidirectionally with these relationships,
0:48 so we could either set the album on the track that maps
0:52 from track to album to the one here, or like you saw in the other example,
0:56 we could go to album.tracks and add this track.
0:59 Either direction has the same effect.
1:02 We can set the details of the track and name, title, whatever.
1:05 Create another track again, set it up with this album
1:09 so now this album has two tracks,
1:11 if we tell the session I'd like to add this album to the database,
1:14 we are almost ready there, so everything is queued up, the unit of work is queued up
1:19 and then we have to commit it and now all those three items
1:22 and their relationships will be created in the database.