Often times in real-world applications we will have entities that are somehow related. Students take courses, customers buy products, and users comment on posts.
In SQLAlchemy we can declare a relationship with a field initialized with the .relationship()
method. In one-to-many relationships, the relationship
field is used on the ‘one’ side of the relationship. In our use case we have the following one-to-many relationships:
- One book ———< many reviews for that book
- One reader ——–< many reviews from that reader
Hence, we add relationship
fields to the Book
and Reader
models. In this exercise, we will show you how to add a relationship to the Book
model, and you will do the same for the Reader
model.
We declare a one-to-many relationship between Book
and Review
by creating the following field in the Book
model:
reviews = db.relationship('Review', backref='book', lazy='dynamic')
where
- the first argument denotes which model is to be on the ‘many’ side of the relationship:
Review
. backref = 'book'
establishes abook
attribute in the related class (in our case, classReview
) which will serve to refer back to the relatedBook
object.lazy = dynamic
makes related objects load as SQLAlchemy’s query objects.
By adding relationship
to Book
we only handled one side in our one-to-many relationship. Specifically, we only covered the direction denoted by the red arrow in the schema below:
In the next exercise, we will add the Review
model and its relationship with the Book
model (the blue arrow).
Instructions
To the Reader
model add a relationship field called reviews
. It should link to Review
with back reference called reviewer
, and should use the dynamic loading process.