Learn

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:

  1. One book ———< many reviews for that book
  2. 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 a book attribute in the related class (in our case, class Review) which will serve to refer back to the related Book 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:

schema

In the next exercise, we will add the Review model and its relationship with the Book model (the blue arrow).

Instructions

1.

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.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?