0
0
Flaskframework~10 mins

Relationships (one-to-many) in Flask - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Relationships (one-to-many)
Define Parent Model
Define Child Model with ForeignKey
Create Parent Instance
Add Child Instances linked to Parent
Query Parent
Access Child Collection via Relationship
This flow shows how to set up a one-to-many relationship in Flask by defining models, linking children to a parent, and accessing related data.
Execution Sample
Flask
class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    books = db.relationship('Book', backref='author')

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
Defines Author and Book models where one Author can have many Books linked by author_id foreign key.
Execution Table
StepActionState ChangeResult
1Define Author model with books relationshipAuthor.books set as collection of Book objectsReady to link books to authors
2Define Book model with author_id foreign keyBook.author_id links to Author.idBooks can reference their author
3Create Author instance (author1)author1.id assigned after commitAuthor record in DB
4Create Book instances (book1, book2) with author_id=author1.idBooks linked to author1Book records in DB linked to author1
5Query author1.booksFetches list of books linked to author1Returns [book1, book2]
6Access book1.authorFetches author linked to book1Returns author1
7ExitAll relationships established and accessibleEnd of flow
💡 All models defined, instances created, and relationships accessed successfully
Variable Tracker
VariableStartAfter Step 3After Step 4Final
author1NoneAuthor instance with id assignedSame instanceSame instance
book1NoneNoneBook instance with author_id=author1.idSame instance
book2NoneNoneBook instance with author_id=author1.idSame instance
author1.booksEmptyEmpty[book1, book2][book1, book2]
book1.authorNoneNoneauthor1author1
Key Moments - 3 Insights
Why do we use db.relationship in the parent model instead of just foreign keys?
db.relationship creates a convenient way to access all related child objects as a list, as shown in step 1 and step 5 of the execution_table, while foreign keys only store the link in the child.
How does Flask know which foreign key links the child to the parent?
The foreign key in the child model (author_id) explicitly references the parent's primary key (author.id), as shown in step 2, so Flask uses this to connect the models.
What happens if you access author1.books before adding any books?
The books collection will be empty, as shown in variable_tracker after step 3, because no Book instances are linked yet.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what does author1.books return?
AAn empty list
BThe author1 instance
CA list containing book1 and book2
DNone
💡 Hint
Check the 'Result' column at step 5 in the execution_table
At which step is the foreign key author_id assigned to book1 and book2?
AStep 4
BStep 3
CStep 5
DStep 2
💡 Hint
Look at the 'Action' and 'State Change' columns in the execution_table
If you remove db.relationship from Author, what will happen when accessing author1.books?
AIt will return all books linked to author1
BIt will raise an AttributeError
CIt will return None
DIt will return author1 instance
💡 Hint
Refer to the importance of db.relationship in step 1 and step 5 of the execution_table
Concept Snapshot
One-to-many relationships in Flask use a foreign key in the child model to link to the parent.
The parent model uses db.relationship to access all related children as a list.
Create parent and child instances, assign foreign keys, then query via relationship.
This setup allows easy navigation from parent to children and vice versa.
Always define foreign keys in child and relationships in parent for clarity.
Full Transcript
In Flask, to create a one-to-many relationship, you define two models: a parent and a child. The child model has a foreign key column that points to the parent's primary key. The parent model uses db.relationship to create a collection of child objects. When you create instances, you assign the parent's id to the child's foreign key. You can then access all children from the parent using the relationship attribute. This setup helps organize related data clearly and access it easily in your application.