Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Using SQLAlchemy
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 connected not split apart like we do in a database. The way we define these
0:16 we add an orm.relationship field to the class so here we have releases so the relationship is against the release type that we're speaking in terms
0:24 of SQLAlchemy entities, not database and then we're going to do an order_by this can either be a single thing or a list. Probably an iterable actually.
0:32 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 We want this relationship to work in both directions so if 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 that 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, packages.id. But them we also would like
1:11 to establish that relationship so we say there's ORM relationship for the package type from release back to the package and it back populates releases
1:20 and it's called Package so you can see the symmetry here not too hard to set these up once you have an example. Put them side by side
1:27 you go okay, here's where I fill in the pieces for my particular dataset 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'll 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 well, it becomes a list and commit those changes
1:51 that'll actually insert the releases. We work in the same but in the reverse as well if we had set the package on a release
1:58 so it's sort of bidirectional in that sense.


Talk Python's Mastodon Michael Kennedy's Mastodon