Search⌘ K
AI Features

The Many-to-Many Relationship

Explore how to implement many-to-many relationships between database models in Flask using SQLAlchemy. This lesson guides you through creating an association table and setting up model relationships, enabling employees to be linked to multiple projects and vice versa.

Introduction #

In the last lessons, we created both a one-to-many and a one-to-one relationship between the Employee and Department models. The code so far is given below.

Python 3.5
class Employee(db.Model):
employee_id = db.Column(db.Integer, primary_key = True)
first_name = db.Column(db.String(50), nullable = False)
last_name = db.Column(db.String(50), nullable = False)
department_name = db.Column(db.String, db.ForeignKey('department.name'), nullable = False)
is_head_of = db.Column(db.String, db.ForeignKey('department.name'), nullable=True)
class Department(db.Model):
name = db.Column(db.String(50), primary_key=True, nullable=False)
location = db.Column(db.String(120), nullable=False)
employees = db.relationship('Employee', backref='department')
head = db.relationship('Employee', backref='head_of_department', uselist=False)
class Project(db.Model):
project_id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(100), nullable=False)

Now, let’s find out how to add a many-to-many relationship between models.

Representing a many-to-many relationship in models #

In the example, a many-to-many relationship should exist between the Employee and the Project. This relationship will indicate that an employee can work on multiple projects while a project can have multiple employees working on it at the same time. ...