The One-to-One Relationship
In this lesson, we will learn how to add a one-to-one relationship between models.
We'll cover the following...
We'll cover the following...
Introduction #
In the last lesson, we created a one-to-many relationship between the Employee and Department models. The code so far is given below:
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)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')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 a one-to-one relationship between these models as well.
Representing a one-to-one relationship in models
In this example, a one-to-one relationship should exist between the Employee and Department. This relationship will indicate that an employee can be the head of a ...