0
0
Flaskframework~10 mins

Many-to-many relationships in Flask - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Many-to-many relationships
Define two models
Create association table
Add relationship fields in models
Create instances
Associate instances via relationship
Query related data
Access linked objects
This flow shows how to set up two models linked by a many-to-many relationship using an association table, then create and query linked data.
Execution Sample
Flask
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy.orm import relationship

db = SQLAlchemy()

association = db.Table('association',
    db.Column('left_id', db.Integer, db.ForeignKey('left.id')),
    db.Column('right_id', db.Integer, db.ForeignKey('right.id'))
)
This code defines an association table to link two models in a many-to-many relationship.
Execution Table
StepActionData Created/ModifiedResult/State
1Define Left and Right modelsLeft and Right classes with id fieldsModels ready for association
2Create association table 'association'Table with left_id and right_id columnsAssociation table links Left and Right
3Add relationship fields to Left and RightLeft.related = relationship(Right, secondary=association, back_populates='left_set') Right.left_set = relationship(Left, secondary=association, back_populates='related')Models linked via association
4Create Left instance l1l1 = Left()l1 created, no relations yet
5Create Right instances r1, r2r1 = Right(), r2 = Right()r1 and r2 created, no relations yet
6Associate l1 with r1 and r2l1.related.append(r1), l1.related.append(r2)l1 linked to r1 and r2
7Commit sessiondb.session.add(l1), db.session.add(r1), db.session.add(r2), db.session.commit()Data saved with links
8Query l1.relatedl1.relatedReturns [r1, r2] showing many-to-many link
9Query r1.left_setr1.left_setReturns [l1] showing reverse link
10EndNo further actionsExecution complete
💡 All objects created and linked; queries confirm many-to-many relationships.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6After Step 7Final
l1NoneLeft instance createdLeft instance createdLinked to r1, r2Persisted in DBLinked to r1, r2
r1NoneNoneRight instance createdLinked to l1Persisted in DBLinked to l1
r2NoneNoneRight instance createdLinked to l1Persisted in DBLinked to l1
Key Moments - 3 Insights
Why do we need an association table for many-to-many relationships?
Because many-to-many means each item in one model can link to many in the other, and vice versa. The association table stores these links as pairs. See Step 2 in execution_table.
How does adding items to the relationship list link objects?
Appending objects to the relationship list adds entries to the association table behind the scenes, creating the link. See Step 6 in execution_table where l1.related.append(r1) links l1 and r1.
How do we access related objects from either side?
We use the relationship attribute on each model. For example, l1.related returns all Right objects linked to l1. See Steps 8 and 9 in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step are the Right instances created?
AStep 4
BStep 6
CStep 5
DStep 7
💡 Hint
Check the 'Action' column for creation of Right instances.
According to variable_tracker, what is the state of l1 after Step 6?
Al1 is linked to r1 and r2
Bl1 is deleted
Cl1 is not linked to any Right instances
Dl1 is linked only to r1
💡 Hint
Look at the 'After Step 6' column for variable l1.
If we skip Step 7 (commit), what happens when querying l1.related?
AIt returns an empty list
BIt returns the linked Right instances anyway
CIt causes an error
DIt returns only one linked instance
💡 Hint
Consider that objects are linked in memory before commit; see Step 6 and 8.
Concept Snapshot
Many-to-many relationships in Flask-SQLAlchemy:
- Use an association table with ForeignKeys to link two models.
- Define relationship() in both models with secondary=association_table and back_populates.
- Append related objects to link them.
- Commit to save links in the database.
- Access related objects via relationship attributes.
Full Transcript
This lesson shows how to create many-to-many relationships in Flask using SQLAlchemy. First, define two models representing the entities you want to link. Then create an association table with foreign keys to both models. Add relationship fields in each model using the association table as secondary and back_populates to enable bidirectional access. Create instances of each model and link them by appending related objects to the relationship list. Commit the session to save changes. You can then query related objects from either side. The execution table traces each step from model definition to querying linked data. The variable tracker shows how instances and their links change over time. Key moments clarify why the association table is needed, how linking works, and how to access related objects. The quiz tests understanding of creation steps, variable states, and effects of committing. This approach helps manage complex many-to-many data connections in Flask apps.