0
0
Flaskframework~20 mins

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

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