Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: Using SQLAchemy
Lecture: Concept: Relationships

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We saw relationships are extremely powerful and let us imagine as if our code and data were just connected almost hierarchically
0:09 the way we would in a regular Python program connect it not split apart like we do in a database. The way we define these
0:16 we had an orm.relationship field to the class. So here we have our releases say the relationship is against the release type
0:23 that we're speaking in terms of SQLAlchemy entities not database and then we're going to do an orderby. This could be a single thing or a list.
0:31 Probably an integer actually and so we're going to pass that in. And then we're going to say it back-populates package. What does that mean?
0:40 If we want this relationship to work in both directions. So we have a package we can see the releases and if we have an individual release
0:45 we can see the single package that it corresponds to. So over in the release we're going to do the package ID value to actually store the relationship
0:55 like we would store any value that's a string or an integer whatever it corresponds to in the other field.
1:01 And then we're going to say this is a foreign key and in the foreign key part we speak in terms of database
1:09 But then we also would like to establish that relationship so we say there's orm relationship for the package type form released back to the package.
1:18 And it back populates releases and it's called package. So you can see the symmetry here. Not too hard to set this up, once you have an example.
1:26 Put them side by side, you go okay here's where I fit all the pieces for my particular data set and then you saw that when we load a package
1:34 it doesn't actually load the releases unless we interact with it. So if we touch it, it would go back to the database and do the query.
1:41 We also saw that if we create new releases and put them into the release package.releases what becomes a list and commit those changes
1:51 that will actually insert the releases. We work on the same but in reverse as well if we had said a package on a release.
1:58 So it's sort of bi-directional in that sense.

Talk Python's Mastodon Michael Kennedy's Mastodon