MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Database Relationships (One-to-Many & Many-to-Many)0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
5.1Flask-SQLAlchemy Setup & Engine Configuration5.2Defining Models & Column Constraints5.3Database Relationships (One-to-Many & Many-to-Many)5.4CRUD Operations, Query Filtering & Pagination5.5Database Schema Migrations with Flask-Migrate
HomeTutorialsFlaskDatabase Relationships (One-to-Many & Many-to-Many)
CRUD Operations, Query Filtering & Pagination

Database Relationships (One-to-Many & Many-to-Many)

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

1from flask_sqlalchemy import SQLAlchemy
2 
3db = SQLAlchemy()
4 
5class Instructor(db.Model):
6 __tablename__ = "instructors"
7
8 id = db.Column(db.Integer, primary_key=True)
9 name = db.Column(db.String(100), nullable=False)
10 email = db.Column(db.String(120), unique=True, nullable=False)
11 
12 # 1:N Relationship
13 # 'courses' property on Instructor returns a list of Course objects
14 # 'back_populates' links to 'instructor' property on Course
15 courses = db.relationship(
16 "Course",
17 back_populates="instructor",
18 cascade="all, delete-orphan",
19 lazy="select"
20 )
21 
22class Course(db.Model):
23 __tablename__ = "courses"
24 
25 id = db.Column(db.Integer, primary_key=True)
26 title = db.Column(db.String(150), nullable=False)
27
28 # Foreign Key column pointing to parent table
29 instructor_id = db.Column(
30 db.Integer,
31 db.ForeignKey("instructors.id", ondelete="CASCADE"),
32 nullable=False
33 )
34 
35 # Relationship linking back to parent
36 instructor = db.relationship("Instructor", back_populates="courses")

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:

Visual Architecture Blueprint
+---------------+              +--------------------+              +------------+
|   students    | <==========> | enrollment_table   | <==========> |  courses   |
+---------------+   (1:N)      +--------------------+   (N:1)      +------------+
| id            |              | student_id (FK)    |              | id         |
| name          |              | course_id  (FK)    |              | title      |
+---------------+              +--------------------+              +------------+
1# Pure association table (no dedicated model class required)
2enrollments = db.Table(
3 "enrollments",
4 db.Column("student_id", db.Integer, db.ForeignKey("students.id", ondelete="CASCADE"), primary_key=True),
5 db.Column("course_id", db.Integer, db.ForeignKey("courses.id", ondelete="CASCADE"), primary_key=True),
6 db.Column("enrolled_at", db.DateTime, default=datetime.utcnow)
7)
8 
9class Student(db.Model):
10 __tablename__ = "students"
11 
12 id = db.Column(db.Integer, primary_key=True)
13 name = db.Column(db.String(100), nullable=False)
14 
15 # Many-to-Many relationship configured using 'secondary'
16 enrolled_courses = db.relationship(
17 "Course",
18 secondary=enrollments,
19 back_populates="enrolled_students",
20 lazy="select"
21 )
22 
23# Inside Course model:
24# enrolled_students = db.relationship("Student", secondary=enrollments, back_populates="enrolled_courses")

3. Working with Related Objects in Python

SQLAlchemy manages relationships transparently using standard Python lists and objects:

1# Create Instructor
2john = Instructor(name="John Doe", email="john@example.com")
3 
4# Assign courses via Python list append
5py_course = Course(title="Python Mastery")
6flask_course = Course(title="Flask Complete Course")
7john.courses.append(py_course)
8john.courses.append(flask_course)
9 
10db.session.add(john)
11db.session.commit()
12 
13# Access reverse relationship
14print(py_course.instructor.name) # Outputs: 'John Doe'

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What column declaration establishes the relational database constraint pointing to a parent table?
Question 2
What is the purpose of db.relationship() in SQLAlchemy?
Question 3
What is required to implement a Many-to-Many relationship in relational databases?
Question 4
What does the cascade="all, delete-orphan" option accomplish?
Question 5
How do you add a Course to a Student's enrolled_courses Many-to-Many relationship?
Next Lesson

CRUD Operations, Query Filtering & Pagination

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Defining Models & Column ConstraintsCRUD Operations, Query Filtering & Pagination

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext