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
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
We declare a one-to-many relationship between
Review by creating the following field in the
reviews = db.relationship('Review', backref='book', lazy='dynamic')
- the first argument denotes which model is to be on the ‘many’ side of the relationship:
backref = 'book'establishes a
bookattribute in the related class (in our case, class
Review) which will serve to refer back to the related
lazy = dynamicmakes related objects load as SQLAlchemy’s query objects.
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).
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.