Search⌘ K
AI Features

The One-to-Many Relationship

Explore how to model one-to-many relationships in Flask database applications using SQLAlchemy. This lesson guides you through defining foreign keys, creating relationships, and using backrefs to link models. By the end, you will understand how to represent real-world relationships like employees belonging to departments within your Flask web applications.

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.

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)
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.

...