The Many-to-Many Relationship
In this lesson, we will learn how to add a many-to-many relationship between models.
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.
Press + to interact
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 ...
Access this course and 1400+ top-rated courses and projects.