Exploring Model Relationships in Flask

tessmueske

Tess Mueske

Posted on September 21, 2024

Exploring Model Relationships in Flask

Coding relationships between classes can be challenging at first! It sounds like a bunch of words thrown together - this thing knows this thing through that thing, but not that other thing. Using real-life examples can be helpful in visualizing those relationships.

For example, say you have some astronauts. Over the course of many years, these astronauts will visit many plants; one planet per mission. So each mission has one astronaut and one planet, and many planets are visited by many astronauts.

In Flask, the relationship between Astronaut and Planet is a many-to-many relationship, while the relationship between Astronaut and Mission and Planet and Mission are both one-to-many. We have three models: The mission model operates as a join table between the astronaut model and the planet model. The classes are called models because they define (or model) the relationships between your data.

So, how do we code these relationships?

I find it easiest to begin with the join table, because I am building out both of the relationships from there.

class Mission(db.Model):
    __tablename__ = 'missions'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
Enter fullscreen mode Exit fullscreen mode

This is what we are starting with for our Mission class.

We know that each mission has one astronaut:

astronaut = db.relationship 
Enter fullscreen mode Exit fullscreen mode

db.relationship defines how two models are related to one another.

Let's connect it to the Astronaut class....

astronaut = db.relationship('Astronaut')
Enter fullscreen mode Exit fullscreen mode

and now let's add the two-way relationship between the two models (Astronaut and Mission):

astronaut = db.relationship('Astronaut', back_populates="missions")
Enter fullscreen mode Exit fullscreen mode

Great work! Since Mission holds both the Astronaut and Planet relationships, let's do the same with planet:

planet = db.relationship('Planet', back_populates="missions")
Enter fullscreen mode Exit fullscreen mode

This is our Mission class with the relationships:

class Mission(db.Model):
    __tablename__ = 'missions'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    astronaut = db.relationship('Astronaut', back_populates="missions")
    planet = db.relationship('Planet', back_populates="missions")

Enter fullscreen mode Exit fullscreen mode

Awesome! Let's go back and take a look at our instructions: The mission model operates as a _join table between the astronaut model and the planet model._
So, we need to link Astronaut to Mission, and Planet to Mission. Let's start with Astronaut:

missions = db.relationship('Mission', back_populates="astronauts")
Enter fullscreen mode Exit fullscreen mode

Missions is plural here, because an astronaut goes on a bunch of them (hopefully!).

And then Planet, which should look similar:

missions = db.relationship('Mission', back_populates="planets")
Enter fullscreen mode Exit fullscreen mode

GREAT! All, together, this looks like:

class Planet(db.Model):
    __tablename__ = 'planets'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    distance_from_earth = db.Column(db.Integer)
    nearest_star = db.Column(db.String)

    missions = db.relationship('Mission', back_populates="planet")


class Astronaut(db.Model):
    __tablename__ = 'astronauts'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    field_of_study = db.Column(db.String)

    missions = db.relationship('Mission', back_populates="astronaut")


class Mission(db.Model):
    __tablename__ = 'missions'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    astronaut = db.relationship('Astronaut', back_populates="astronauts")
    planet = db.relationship('Planet', back_populates="missions")

Enter fullscreen mode Exit fullscreen mode

Lastly, let's add our foreign keys to our missions table. A foreign key is an integer that references an item in another database that links the two together. For example, astronaut 1's foreign key is 1 in the mission table, so every time we see the number 1 in that column, we know it applies to that astronaut!

Mission is the only class that needs foreign keys, since it is in charge of all the relationships.

class Mission(db.Model, SerializerMixin):
    __tablename__ = 'missions'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    astronaut_id = db.Column(db.Integer, db.ForeignKey('astronauts.id'))
    planet_id = db.Column(db.Integer, db.ForeignKey('planets.id'))

    astronaut = db.relationship('Astronaut', back_populates="missions")
    planet = db.relationship('Planet', back_populates="missions")

    serialize_rules = ('-astronaut.missions', '-astronaut.planets')
Enter fullscreen mode Exit fullscreen mode

Fantastic job! We've set up some relationships between our models. Thanks for coding!

Sources: Thank you to Flatiron School for this lab! I changed the class name 'Scientist' to 'Astronaut'.

💖 💪 🙅 🚩
tessmueske
Tess Mueske

Posted on September 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Exploring Model Relationships in Flask