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
0:02 and let us imagine as if our code and data
0:06 were just connected almost hierarchically
0:08 the way we would in a regular Python program connect it
0:12 not split apart like we do in a database.
0:14 The way we define these
0:15 we had an orm.relationship field to the class.
0:18 So here we have our releases
0:19 say the relationship is against the release type
0:22 that we're speaking in terms of SQLAlchemy entities
0:25 not database and then we're going to do an orderby.
0:27 This could be a single thing or a list.
0:30 Probably an integer actually
0:32 and so we're going to pass that in.
0:34 And then we're going to say it back-populates package.
0:38 What does that mean?
0:39 If we want this relationship to work in both directions.
0:41 So we have a package we can see the releases
0:43 and if we have an individual release
0:44 we can see the single package that it corresponds to.
0:48 So over in the release we're going to do the package ID value
0:52 to actually store the relationship
0:54 like we would store any value that's a string or an integer
0:57 whatever it corresponds to in the other field.
1:00 And then we're going to say this is a foreign key
1:02 and in the foreign key part we speak in terms of database
1:08 But then we also would like to establish that relationship
1:11 so we say there's orm relationship
1:13 for the package type form released back to the package.
1:17 And it back populates releases and it's called package.
1:20 So you can see the symmetry here.
1:22 Not too hard to set this up, once you have an example.
1:25 Put them side by side, you go okay
1:27 here's where I fit all the pieces for my particular data set
1:30 and then you saw that when we load a package
1:33 it doesn't actually load the releases
1:35 unless we interact with it.
1:37 So if we touch it, it would go back to the database
1:39 and do the query.
1:40 We also saw that if we create new releases
1:43 and put them into the release package.releases
1:46 what becomes a list and commit those changes
1:50 that will actually insert the releases.
1:52 We work on the same but in reverse as well
1:54 if we had said a package on a release.
1:57 So it's sort of bi-directional in that sense.