Bird
Raised Fist0
Flaskframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does a one-to-many relationship in Flask SQLAlchemy represent?
easy
A. One record in a table is linked to many records in another table
B. Many records in a table are linked to one record in another table
C. Two tables have the same number of records
D. One record is linked to exactly one record in another table

Solution

  1. Step 1: Understand the meaning of one-to-many

    One-to-many means one item in the first table relates to multiple items in the second table.
  2. Step 2: Match the description to options

    One record in a table is linked to many records in another table correctly describes this relationship as one record linked to many records.
  3. Final Answer:

    One record in a table is linked to many records in another table -> Option A
  4. Quick Check:

    One-to-many = One record linked to many [OK]
Hint: One-to-many means one item connects to many items [OK]
Common Mistakes:
  • Confusing one-to-many with many-to-one
  • Thinking it means equal number of records
  • Assuming one-to-many means one-to-one
2. Which of the following is the correct way to define a one-to-many relationship in Flask SQLAlchemy models?
easy
A. Both B and C together
B. child_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
C. parent = db.relationship('Child', backref='parent', lazy=True)
D. db.relationship('Parent', foreign_key='child.id')

Solution

  1. Step 1: Identify relationship and foreign key usage

    In Flask SQLAlchemy, one-to-many needs a relationship on the parent and a foreign key on the child.
  2. Step 2: Check options for correct syntax

    parent = db.relationship('Child', backref='parent', lazy=True) shows the relationship on the parent, child_id = db.Column(db.Integer, db.ForeignKey('parent.id')) shows the foreign key on the child. Both are needed together.
  3. Final Answer:

    Both B and C together -> Option A
  4. Quick Check:

    Relationship + ForeignKey = Correct one-to-many [OK]
Hint: Use relationship on parent and ForeignKey on child [OK]
Common Mistakes:
  • Defining only relationship without foreign key
  • Using wrong foreign key syntax
  • Confusing parent and child roles
3. Given these models, what will author.books return?
class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    books = db.relationship('Book', backref='author')

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))

# Assume author is an Author instance with 3 related Book records
medium
A. A single Book object
B. A list of Book objects related to the author
C. An integer count of books
D. null, because books is not defined

Solution

  1. Step 1: Understand db.relationship returns

    The relationship attribute returns a list-like collection of related objects in one-to-many.
  2. Step 2: Apply to author.books

    Since author.books is a relationship to Book, it returns a list of Book objects linked to that author.
  3. Final Answer:

    A list of Book objects related to the author -> Option B
  4. Quick Check:

    Relationship attribute returns list of related objects [OK]
Hint: Relationship attribute returns list of related items [OK]
Common Mistakes:
  • Expecting a single object instead of a list
  • Thinking it returns count instead of objects
  • Assuming attribute is undefined
4. Identify the error in this Flask SQLAlchemy one-to-many setup:
class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship('Child')

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer)
medium
A. children should be a db.Column, not relationship
B. Relationship should be on Child, not Parent
C. Missing ForeignKey on Child's parent_id column
D. Parent model missing primary key

Solution

  1. Step 1: Check Child model's parent_id column

    It lacks the ForeignKey constraint linking to Parent's id.
  2. Step 2: Understand relationship requires ForeignKey

    Without ForeignKey, SQLAlchemy cannot link Child to Parent properly.
  3. Final Answer:

    Missing ForeignKey on Child's parent_id column -> Option C
  4. Quick Check:

    ForeignKey needed on child foreign key column [OK]
Hint: ForeignKey must be on child foreign key column [OK]
Common Mistakes:
  • Forgetting ForeignKey on child side
  • Placing relationship on wrong model
  • Confusing relationship with column
5. You want to query all books written by an author named 'Alice' using Flask SQLAlchemy with one-to-many models Author and Book. Which code snippet correctly achieves this?
hard
A. author = Author.query.filter_by(name='Alice').all()\nbooks = author.books if author else []
B. books = Book.query.filter(author.name == 'Alice').all()
C. books = Book.query.filter_by(author='Alice').all()
D. books = Book.query.join(Author).filter(Author.name == 'Alice').all()

Solution

  1. Step 1: Understand querying with relationships

    To filter books by author name, join Book with Author and filter by Author.name.
  2. Step 2: Analyze options for correct query

    books = Book.query.join(Author).filter(Author.name == 'Alice').all() uses join and filter correctly to get all books by 'Alice'. author = Author.query.filter_by(name='Alice').all()\nbooks = author.books if author else [] accesses .books on list of authors (from .all()). books = Book.query.filter(author.name == 'Alice').all() uses invalid reference to 'author'. books = Book.query.filter_by(author='Alice').all() filters by author string incorrectly.
  3. Final Answer:

    books = Book.query.join(Author).filter(Author.name == 'Alice').all() -> Option D
  4. Quick Check:

    Use join and filter on related model for correct query [OK]
Hint: Use join and filter on related model for queries [OK]
Common Mistakes:
  • Using .all() instead of .first() when accessing instance relationship
  • Referencing related model without qualifier in filter
  • Not joining tables before filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard