Challenge - 5 Problems
Lazy vs Eager Loading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Understanding lazy loading behavior in Flask-SQLAlchemy
In Flask-SQLAlchemy, what happens when you access a related object configured with lazy='select' for the first time?
Attempts:
2 left
💡 Hint
Think about when the database query for the related object happens.
✗ Incorrect
Lazy loading with lazy='select' means the related data is fetched only when you access it, not when the parent is loaded.
❓ component_behavior
intermediate2:00remaining
Eager loading effect on query count
Given a Flask-SQLAlchemy model with a relationship set to eager loading using
joined, what is the effect on the number of database queries when fetching parent objects?Attempts:
2 left
💡 Hint
Eager loading tries to reduce the number of queries by fetching related data upfront.
✗ Incorrect
Eager loading with joined uses a SQL JOIN to get parent and related objects in one query, reducing database hits.
❓ state_output
advanced2:00remaining
Output of query count with lazy loading
Consider this Flask-SQLAlchemy code snippet where
lazy='select' is used. What will be the total number of SQL queries executed when iterating over 3 parent objects and accessing their related child objects?Flask
parents = Parent.query.all() for p in parents: print(p.child.name)
Attempts:
2 left
💡 Hint
Remember lazy loading triggers a query each time a related attribute is accessed if not already loaded.
✗ Incorrect
Lazy loading runs one query to get all parents, then one query per parent to get each child when accessed.
🔧 Debug
advanced2:00remaining
Fixing N+1 query problem with eager loading
You notice your Flask app runs many queries when accessing related objects, causing slow response. Which change fixes this N+1 query problem?
Flask
parents = Parent.query.all() for p in parents: print(p.child.name)
Attempts:
2 left
💡 Hint
Eager loading can reduce queries by fetching related data upfront.
✗ Incorrect
Using joinedload tells SQLAlchemy to fetch related objects in the same query, avoiding multiple queries.
📝 Syntax
expert2:00remaining
Correct syntax for eager loading with subquery in Flask-SQLAlchemy
Which option correctly applies subquery eager loading to a relationship named
items in a Flask-SQLAlchemy query?Flask
results = Order.query.options(_____).all()
Attempts:
2 left
💡 Hint
Look for the correct function to pass inside options() for subquery loading.
✗ Incorrect
subqueryload() is the correct function to specify subquery eager loading in SQLAlchemy queries.