The One-to-Many Relationship
In this lesson, we will get to know how to add a one-to-many relationship between models.
Introduction #
While working with databases, one of the key concepts is the relationship between tables. The types of relationships that exist are:
- One-to-many
- One-to-one
- Many-to-many
In the next few lessons, we will cover how to represent and create these relationships between the models using SQLAlchemy
.
Consider the Human Resource Management System(HRMS) of a company. The application would contain the following models.
Employee
Department
Project
A simple implementation of these models 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)class Department(db.Model):name = db.Column(db.String(50), nullable = False)location = db.Column(db.String(120), nullable = 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 learn how to add relationships between these models.
...