In Flask SQLAlchemy, limit() must be called before all() because all() executes the query and returns a list.
Step 2: Identify error cause
Calling limit() on a list (result of all()) causes an AttributeError.
Final Answer:
Calling limit() after all() causes an error -> Option A
Quick Check:
limit() after all() = error [OK]
Hint: Call limit() before all() to avoid errors [OK]
Common Mistakes:
Calling limit() after all()
Thinking all() returns a query object
Misplacing filter parentheses
5. You want to optimize a query to fetch only the usernames of active users, limiting results to 20. Which is the best approach?
hard
A. User.query.with_entities(User.username).filter(User.active == True).limit(20).all()
B. User.query.filter(User.active == True).all()[:20]
C. User.query.all().filter(User.active == True).limit(20)
D. User.query.filter(User.active == True).limit(20).all()
Solution
Step 1: Select only needed fields
Using with_entities(User.username) fetches only usernames, reducing data load.
Step 2: Apply filter and limit correctly
Filter active users and limit results to 20 before executing with all().
Step 3: Evaluate other options
User.query.filter(User.active == True).limit(20).all() fetches full user objects, not optimized. User.query.all().filter(User.active == True).limit(20) calls all() before filter, causing error. User.query.filter(User.active == True).all()[:20] fetches all then slices in Python, inefficient.
Final Answer:
User.query.with_entities(User.username).filter(User.active == True).limit(20).all() -> Option A
Quick Check:
Select fields + filter + limit = D [OK]
Hint: Use with_entities() to select fields, then filter and limit [OK]
Common Mistakes:
Fetching full objects instead of specific fields
Calling all() before filter or limit
Slicing results in Python instead of limiting in query
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.