Skip to main content
In SQLAlchemy, relationships are represented using:
  • ForeignKey() → Creates the database-level relationship.
  • relationship() → Creates the Python object relationship.
  • back_populates → Enables navigation in both directions.

Relationship Types

One-to-One (1:1)

One record in one table is associated with exactly one record in another table. Examples
  • One Person → One Passport
  • One Employee → One Parking Space

SQLAlchemy Implementation

Key Points

  • Uses ForeignKey() to link the tables.
  • Uses unique=True to ensure one passport belongs to only one person.
  • Uses uselist=False so person.passport returns a single object instead of a list.

One-to-Many (1:N)

One record in one table is associated with multiple records in another table. Examples
  • One Course → Many Students
  • One Department → Many Employees
  • One Customer → Many Orders

SQLAlchemy Implementation

Key Points

  • The foreign key is stored in the many side (Student).
  • The one side (Course) contains a list of students.
  • One course can have many students.

Many-to-One (N:1)

Many records in one table are associated with one record in another table. Examples
  • Many Students → One Course
  • Many Employees → One Department
  • Many Orders → One Customer

SQLAlchemy Implementation

Key Points

  • The foreign key is stored in the many side (Student).
  • Each student belongs to one course.
  • A many-to-one relationship is simply the reverse view of a one-to-many relationship.

Many-to-Many (N:N)

Many records in one table are associated with many records in another table. Examples
  • Many Students → Many Courses
  • Many Doctors → Many Patients
  • Many Authors → Many Books
Since one table cannot directly store multiple foreign keys for another table, an association (junction) table is required.

SQLAlchemy Implementation

Association Table

Student Model

Course Model

Key Points

  • Uses an association table to connect the two tables.
  • Neither table contains a direct foreign key to the other.
  • secondary specifies the association table.
  • One student can enroll in many courses.
  • One course can have many students.

Summary

Key Points

  • ForeignKey() creates the relationship in the database.
  • relationship() creates the relationship between Python objects.
  • back_populates enables navigation from both models.
  • uselist=False is used for one-to-one relationships.
  • secondary is used only for many-to-many relationships.
  • The foreign key is usually stored on the many side of the relationship.
  • One-to-Many and Many-to-One are two views of the same relationship.