Adding a CMS to Your Flask Web App Transcripts
Chapter: Appendix: Using SQlAlchemy
Lecture: Concept: Relationships
We saw relationships are extremely powerful and let us imagine as if our code and data were just connected, almost hierarchically
the way we would in a regular Python program connected not split apart like we do in a database. The way we define these
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
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.
And so, we're going to pass that in and then we're going to say it back populates package. What does that mean?
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.
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
like we would store any value that's a string or an integer whatever it corresponds to in that other field.
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
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
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
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
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.
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
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
so it's sort of bidirectional in that sense.