Bird
Raised Fist0
Flaskframework~20 mins

Many-to-many relationships in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Many-to-many Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask SQLAlchemy many-to-many query?

Given two models Author and Book connected by a many-to-many relationship through author_book table, what will print([book.title for book in author.books]) output after adding two books to an author?

Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

author_book = db.Table('author_book',
    db.Column('author_id', db.Integer, db.ForeignKey('author.id')),
    db.Column('book_id', db.Integer, db.ForeignKey('book.id'))
)

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    books = db.relationship('Book', secondary=author_book, back_populates='authors')

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    authors = db.relationship('Author', secondary=author_book, back_populates='books')

# Create author and books
author = Author(name='Alice')
book1 = Book(title='Flask Basics')
book2 = Book(title='Advanced Flask')
author.books.append(book1)
author.books.append(book2)

print([book.title for book in author.books])
A['Alice']
B['Flask Basics']
C['Flask Basics', 'Advanced Flask']
D[]
Attempts:
2 left
💡 Hint

Think about what author.books contains after appending two book objects.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a many-to-many relationship in Flask SQLAlchemy?

Choose the correct code snippet that defines a many-to-many relationship between Student and Course models using an association table.

A
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    courses = db.relationship('Course', backref='students')

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
B
enrollments = db.Table('enrollments',
    db.Column('student_id', db.Integer, db.ForeignKey('student.id')),
    db.Column('course_id', db.Integer, db.ForeignKey('course.id'))
)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    courses = db.relationship('Course', secondary=enrollments, back_populates='students')

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    students = db.relationship('Student', secondary=enrollments, back_populates='courses')
C
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    courses = db.relationship('Course')

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
D
enrollments = db.Table('enrollments',
    db.Column('student_id', db.Integer),
    db.Column('course_id', db.Integer)
)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    courses = db.relationship('Course', secondary=enrollments)
Attempts:
2 left
💡 Hint

Remember the association table needs foreign keys and both sides should use secondary with back_populates.

🔧 Debug
advanced
2:00remaining
Why does this many-to-many relationship code raise an error?

Consider this code snippet. Why does it raise an error when trying to add a book to an author?

Flask
author_book = db.Table('author_book',
    db.Column('author_id', db.Integer, db.ForeignKey('author.id')),
    db.Column('book_id', db.Integer, db.ForeignKey('book.id'))
)

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    books = db.relationship('Book', secondary=author_book)

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

# Usage
author = Author(name='Bob')
book = Book(title='Flask Tips')
author.books.append(book)
db.session.add(author)
db.session.commit()
ABecause the Book instance is not added to the session before commit
BBecause the association table is missing a primary key
CBecause the relationship lacks back_populates causing a runtime error
DBecause the author object is missing a name attribute
Attempts:
2 left
💡 Hint

Think about what SQLAlchemy needs to track objects before committing.

❓ state_output
advanced
2:00remaining
What is the value of len(course.students) after these operations?

Given Student and Course models with a many-to-many relationship, what is the length of course.students after adding two students but removing one?

Flask
enrollments = db.Table('enrollments',
    db.Column('student_id', db.Integer, db.ForeignKey('student.id')),
    db.Column('course_id', db.Integer, db.ForeignKey('course.id'))
)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    courses = db.relationship('Course', secondary=enrollments, back_populates='students')

class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    students = db.relationship('Student', secondary=enrollments, back_populates='courses')

student1 = Student(name='John')
student2 = Student(name='Jane')
course = Course(title='Math 101')

course.students.append(student1)
course.students.append(student2)
course.students.remove(student1)

print(len(course.students))
A1
B2
C0
DRaises ValueError
Attempts:
2 left
💡 Hint

Think about what happens when you remove one student from the list.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of the association table in many-to-many relationships?

In Flask SQLAlchemy many-to-many relationships, what is the main purpose of the association table?

AIt automatically creates one-to-one relationships between the two models
BIt stores all data fields of both related models in one table to optimize queries
CIt replaces the need for foreign keys by storing object references directly
DIt stores foreign keys linking two tables and allows SQLAlchemy to track their connections without extra model class
Attempts:
2 left
💡 Hint

Think about what the association table contains and why it is needed.

Practice

(1/5)
1. What is the main purpose of using an association table in a many-to-many relationship in Flask SQLAlchemy?
easy
A. To link two tables that can have multiple related records each
B. To store user login information securely
C. To create a one-to-one relationship between models
D. To optimize database queries by caching results

Solution

  1. Step 1: Understand many-to-many relationships

    Many-to-many means each record in one table can relate to many records in another table, and vice versa.
  2. Step 2: Role of association table

    An association table connects these two tables by holding pairs of related record IDs, enabling the many-to-many link.
  3. Final Answer:

    To link two tables that can have multiple related records each -> Option A
  4. Quick Check:

    Association table = link many-to-many tables [OK]
Hint: Association tables connect two models with many links [OK]
Common Mistakes:
  • Thinking association tables store user credentials
  • Confusing many-to-many with one-to-one relationships
  • Assuming association tables optimize queries automatically
2. Which of the following is the correct way to define an association table in Flask SQLAlchemy?
easy
A. association = db.Model('association', db.Column('left_id', db.Integer), db.Column('right_id', db.Integer))
B. association = db.Model('association', db.ForeignKey('left.id'), db.ForeignKey('right.id'))
C. association = db.Table('association', db.Column('left_id', db.String), db.Column('right_id', db.String))
D. association = db.Table('association', db.Column('left_id', db.Integer, db.ForeignKey('left.id')), db.Column('right_id', db.Integer, db.ForeignKey('right.id')))

Solution

  1. Step 1: Identify correct association table syntax

    Association tables use db.Table with columns having foreign keys to related tables.
  2. Step 2: Check options for correct use of db.Table and foreign keys

    association = db.Table('association', db.Column('left_id', db.Integer, db.ForeignKey('left.id')), db.Column('right_id', db.Integer, db.ForeignKey('right.id'))) correctly uses db.Table and defines columns with foreign keys to 'left.id' and 'right.id'.
  3. Final Answer:

    association = db.Table('association', db.Column('left_id', db.Integer, db.ForeignKey('left.id')), db.Column('right_id', db.Integer, db.ForeignKey('right.id'))) -> Option D
  4. Quick Check:

    Association table = db.Table + foreign keys [OK]
Hint: Use db.Table with foreign keys for association tables [OK]
Common Mistakes:
  • Using db.Model instead of db.Table for association tables
  • Missing foreign key constraints in columns
  • Using wrong data types like String for IDs
3. Given the following models, what will print(user.groups[0].name) output?
association = db.Table('association',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('group_id', db.Integer, db.ForeignKey('group.id'))
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    groups = db.relationship('Group', secondary=association, back_populates='users')

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    users = db.relationship('User', secondary=association, back_populates='groups')

user = User(name='Alice')
group = Group(name='Admins')
user.groups.append(group)
print(user.groups[0].name)
medium
A. None
B. Admins
C. Alice
D. Error: AttributeError

Solution

  1. Step 1: Understand relationship setup

    User and Group are linked many-to-many via association table. User.groups holds Group objects.
  2. Step 2: Analyze code behavior

    User 'Alice' has 'Admins' group appended. Accessing user.groups[0].name returns 'Admins'.
  3. Final Answer:

    Admins -> Option B
  4. Quick Check:

    user.groups[0].name = 'Admins' [OK]
Hint: Access related objects via relationship lists [OK]
Common Mistakes:
  • Confusing user name with group name
  • Expecting None if not committed to DB
  • Assuming error due to missing session commit
4. Identify the error in this many-to-many relationship setup:
association = db.Table('association',
    db.Column('user_id', db.Integer),
    db.Column('group_id', db.Integer)
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    groups = db.relationship('Group', secondary=association, back_populates='users')

class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    users = db.relationship('User', secondary=association, back_populates='groups')
medium
A. Incorrect use of back_populates attribute
B. Missing primary key in User model
C. Missing foreign key constraints in association table columns
D. Using db.Model instead of db.Table for association

Solution

  1. Step 1: Check association table columns

    Columns lack foreign key constraints linking to User and Group tables.
  2. Step 2: Importance of foreign keys

    Foreign keys are required to enforce relationships and enable SQLAlchemy to join tables properly.
  3. Final Answer:

    Missing foreign key constraints in association table columns -> Option C
  4. Quick Check:

    Foreign keys required in association table [OK]
Hint: Always add foreign keys in association tables [OK]
Common Mistakes:
  • Omitting foreign keys in association table
  • Confusing back_populates usage
  • Thinking primary key is missing in User model
5. You want to add a role attribute to the association between User and Group models to store the user's role in each group. Which approach correctly implements this in Flask SQLAlchemy?
hard
A. Create a new model class for the association with user_id, group_id, and role columns
B. Add a role column to the association table defined with db.Table
C. Add role as a property in the User model
D. Add role as a property in the Group model

Solution

  1. Step 1: Understand limitation of db.Table

    db.Table is a simple table without a model class, so it cannot hold extra attributes like 'role'.
  2. Step 2: Use association object pattern

    Create a new model class representing the association with foreign keys and extra columns like 'role'. This allows storing additional data per relationship.
  3. Final Answer:

    Create a new model class for the association with user_id, group_id, and role columns -> Option A
  4. Quick Check:

    Extra data in many-to-many needs association model class [OK]
Hint: Use association model class for extra fields in many-to-many [OK]
Common Mistakes:
  • Trying to add extra columns to db.Table association
  • Adding role to User or Group instead of association
  • Not using a model class for complex associations
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