Database Relationships (One-to-Many & Many-to-Many)
Database Relationships (One-to-Many & Many-to-Many)
Real-world applications require relationships between entities: users write articles, courses contain lessons, and students enroll in multiple classes. SQLAlchemy models relationships using Foreign Keys and Relationship Mappings.
1. One-to-Many Relationship (1:N)
In a One-to-Many relationship, one parent record owns multiple child records (e.g., one Instructor has many Course offerings).
Cascade Rules:
Setting cascade="all, delete-orphan" ensures that if an Instructor is deleted from the database, all associated child Course records are automatically deleted as well, preventing orphaned records.
2. Many-to-Many Relationship (M:N)
In a Many-to-Many relationship, multiple students can enroll in multiple courses. This requires a third helper table called an Association Table:
+---------------+ +--------------------+ +------------+ | students | <==========> | enrollment_table | <==========> | courses | +---------------+ (1:N) +--------------------+ (N:1) +------------+ | id | | student_id (FK) | | id | | name | | course_id (FK) | | title | +---------------+ +--------------------+ +------------+
3. Working with Related Objects in Python
SQLAlchemy manages relationships transparently using standard Python lists and objects:
Practice Quiz
db.relationship() in SQLAlchemy?cascade="all, delete-orphan" option accomplish?Course to a Student's enrolled_courses Many-to-Many relationship?CRUD Operations, Query Filtering & Pagination
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Defining Models & Column Constraints | CRUD Operations, Query Filtering & Pagination |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.