Bird
0
0

Given the following Flask-SQLAlchemy code, what happens when print(user.posts) is executed?

medium📝 component behavior Q4 of 15
Flask - Performance Optimization
Given the following Flask-SQLAlchemy code, what happens when print(user.posts) is executed?
user = User.query.first()
print(user.posts)

Assuming posts relationship is defined with lazy='select'.
AAn error occurs because posts are not loaded.
BPosts are already loaded with the user in the first query.
CA separate query is executed to load posts when accessed.
DPosts are never loaded and print shows empty list.
Step-by-Step Solution
Solution:
  1. Step 1: Understand lazy='select' behavior

    With lazy='select', related posts are not loaded initially but fetched when accessed.
  2. Step 2: Analyze code execution

    When print(user.posts) runs, it triggers a separate query to load posts.
  3. Final Answer:

    A separate query is executed to load posts when accessed. -> Option C
  4. Quick Check:

    lazy='select' triggers query on access [OK]
Quick Trick: lazy='select' loads related data on attribute access [OK]
Common Mistakes:
MISTAKES
  • Assuming posts load with user query
  • Expecting error due to lazy loading
  • Thinking posts remain empty

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes