Skip to content

SQLAlchemy One to many Relationship

Rajesh Khadka edited this page Nov 25, 2019 · 1 revision

The employee has many education histories. To keep the relationship between to entity we will have the following code.

Employee

class Employee(db.Model):
    __tablename__ = 'employees'

    def __init__(self,
                 name,
                 age,
                 gender,
                 phone):
        self.name = name
        self.age = age
        self.gender = gender
        self.phone = phone

    id = db.Column(db.String(), primary_key=True, unique=True, nullable=False, default=str(uuid.uuid4()))
    name = db.Column(db.String(), nullable=False)
    age = db.Column(db.String(), nullable=False)
    gender = db.Column(db.String(), nullable=False)
    phone = db.Column(db.String(), nullable=False)
    educations = db.relationship('Education', back_populates='employee')

    def to_dict(self):
        return {
            'name': self.name,
            'age': self.age,
            'gender': self.gender,
            'phone': self.phone
        }

Education

class Education(db.Model):
    __tablename__ = 'educations'

    def __init__(self,
                 degree,
                 field_of_study,
                 start_date,
                 end_date,
                 institution,
                 grade,
                 description):
        self.degree = degree
        self.field_of_study = field_of_study
        self.start_date = start_date
        self.end_date = end_date
        self.institution = institution
        self.grade = grade
        self.description = description

    id = db.Column(db.String(), primary_key=True, unique=True, nullable=False, default=str(uuid.uuid4()))
    degree = db.Column(db.String(), nullable=False)
    field_of_study = db.Column(db.String(), nullable=False)
    start_date = db.Column(db.Date(), nullable=False)
    end_date = db.Column(db.Date(), nullable=False)
    institution = db.Column(db.String(), nullable=False)
    grade = db.Column(db.String(), nullable=False)
    description = db.Column(db.String(), nullable=False)
    employee_id = db.Column(db.String(), ForeignKey('employees.id'))
    employee = db.relationship('Employee', back_populates='educations')

Let's know more about the relationship:

To maintain the one to many relationships we need to make the foreign key of parent table in child table. In our case, we have referenced the id employee table in education table as :

employee_id = db.Column(db.String(), ForeignKey('employees.id'))
# here employees.id is the name_of_table.id

Now we have to maintain the relationship to access the attribute as an object in both tables. We may have the use case for accessing like as an employee.educations or education.employee while developing the project. we can maintain a relationship like as an:

## in employee table
educations = db.relationship('Education', back_populates='employee')

## in educations table
employee = db.relationship('Employee', back_populates='educations')

Here back_populates='employee' creates the link with the field of educations in Employee class. Same as in the Employee class back_populates='employee' creates the link with the field employee in Educations class.

You can explore various operations that can be performed over the sample code here.

Clone this wiki locally