Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Using SQLAlchemy
Lecture: Concept: Relationships
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 connected
0:12 not split apart like we do in a database.
0:14 The way we define these
0:15 we add an orm.relationship field to the class
0:18 so here we have releases
0:19 so the relationship is against the release type
0:22 that we're speaking in terms
0:23 of SQLAlchemy entities, not database
0:26 and then we're going to do an order_by
0:27 this can either be a single thing or a list.
0:30 Probably an iterable actually.
0:31 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 We want this relationship to work in both directions
0:41 so if we have a package
0:42 we can see the releases
0:43 and if we have an individual release.
0:44 We can see the single package
0:46 that it corresponds to.
0:48 So, over in the release
0:49 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
0:57 or an integer
0:58 whatever it corresponds to in that other field.
1:00 And then we're going to say this is a foreign key
1:02 and in the foreign key part
1:04 we speak in terms of database, packages.id.
1:08 But them we also would like
1:10 to establish that relationship
1:11 so we say there's ORM relationship
1:13 for the package type from release back to the package
1:17 and it back populates releases
1:19 and it's called Package
1:20 so you can see the symmetry here
1:22 not too hard to set these up
1:23 once you have an example.
1:25 Put them side by side
1:26 you go okay, here's where I fill in the pieces
1:28 for my particular dataset
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
1:38 it'll go back to the database 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:47 well, it becomes a list
1:48 and commit those changes
1:50 that'll actually insert the releases.
1:52 We work in the same but in the reverse as well
1:54 if we had set the package on a release
1:57 so it's sort of bidirectional in that sense.