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. We've seen the unit of work in action with this session and inserting objects are no different.
0:10 So again, we are going to use a session factory to create a session and then to insert new objects, we just create new instances
0:15 at the types that map to those particular tables. So if we want to create a new album, we just create a new album,
0:21 and we are going to set some properties. In the example you saw me write the code, I actually use name value keyword arguments to set the name
0:29 and the year in the album initializer. But, you could just as well create them and sat them like this in an operative way
0:36 and that would be totally fine. This is not yet putting the database, we are still going to have to add it to the session,
0:41 we also want to associate some tracks with this album, so we are going to create a new track.
0:46 And we can actually go bidirectionally with these relationships, so we could either set the album on the track that maps
0:53 from track to album to the one here, or like you saw in the other example, we could go to album.tracks and add this track.
1:00 Either direction has the same effect. We can set the details of the track and name, title, whatever.
1:06 Create another track again, set it up with this album so now this album has two tracks,
1:12 if we tell the session I'd like to add this album to the database, we are almost ready there, so everything is queued up, the unit of work is queued up
1:20 and then we have to commit it and now all those three items and their relationships will be created in the database.

Talk Python's Mastodon Michael Kennedy's Mastodon