Challenge - 5 Problems
One-to-Many Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this Flask-SQLAlchemy one-to-many relationship query?
Given the models Author and Book with a one-to-many relationship, what will be printed by the following code?
Flask
author = Author.query.filter_by(name='Alice').first() print(len(author.books))
Attempts:
2 left
💡 Hint
Remember that 'books' is the related collection for the one-to-many relationship from Author to Book.
✗ Incorrect
The 'books' attribute on the Author model returns a list of Book objects related to that author. So, len(author.books) gives the count of books written by Alice.
📝 Syntax
intermediate2:00remaining
Which option correctly defines a one-to-many relationship in Flask-SQLAlchemy?
Choose the correct way to define a one-to-many relationship between Author and Book models.
Attempts:
2 left
💡 Hint
The foreign key should be on the 'many' side, and the relationship on the 'one' side.
✗ Incorrect
Option A correctly places the foreign key on the Book model and defines the relationship on the Author model with a back reference.
🔧 Debug
advanced2:00remaining
Why does accessing author.books raise an error in this code?
Given these models, why does the code 'author = Author.query.first(); print(author.books)' raise an AttributeError?
Flask
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) class Book(db.Model): id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
Attempts:
2 left
💡 Hint
Check if the Author model knows about its related books.
✗ Incorrect
The Author model does not define a relationship to Book, so 'author.books' does not exist and raises AttributeError.
❓ state_output
advanced2:00remaining
What is the value of book.author.name after this code runs?
Given these models and data, what will 'print(book.author.name)' output?
Flask
author = Author(name='Bob') db.session.add(author) db.session.commit() book = Book(title='Flask Guide', author_id=author.id) db.session.add(book) db.session.commit() book = Book.query.first() print(book.author.name)
Attempts:
2 left
💡 Hint
The 'author' attribute on Book is set by the backref from the relationship.
✗ Incorrect
The backref 'author' on Book points to the Author object, so 'book.author.name' returns 'Bob'.
🧠 Conceptual
expert2:00remaining
Which statement best describes the behavior of lazy='dynamic' in a one-to-many relationship?
In Flask-SQLAlchemy, what does setting lazy='dynamic' on a one-to-many relationship do?
Attempts:
2 left
💡 Hint
Think about how you can chain filters on the related collection.
✗ Incorrect
Setting lazy='dynamic' returns a query object for the related items, so you can add filters or limits before fetching data.