📖 Scenario: You are building a simple Flask web app that shows a list of books from a database. The database has many books, but you want to show only the books with more than 300 pages to users.
🎯 Goal: Build a Flask app that queries the database efficiently to get only books with more than 300 pages and displays their titles.
📋 What You'll Learn
Create a list of book dictionaries with title and pages
Add a variable to set the minimum page count filter
Use a list comprehension to select books with pages greater than the filter
Create a Flask route to display the filtered book titles
💡 Why This Matters
🌍 Real World
Filtering data before sending it to users helps apps run faster and use less memory.
💼 Career
Knowing how to optimize queries and filter data efficiently is important for backend web development jobs.
Progress0 / 4 steps
1
Create the book data list
Create a list called books with these exact dictionaries: {'title': 'Python Basics', 'pages': 250}, {'title': 'Flask Web Development', 'pages': 350}, {'title': 'Advanced Python', 'pages': 400}
Flask
Hint
Use a list with dictionaries. Each dictionary has keys 'title' and 'pages'.
2
Set the minimum page count filter
Create a variable called min_pages and set it to 300 to filter books with more than 300 pages
Flask
Hint
Just create a variable named min_pages and assign 300.
3
Filter books with list comprehension
Create a list called filtered_books using a list comprehension that includes only books from books where the pages value is greater than min_pages
Flask
Hint
Use a list comprehension with book for book in books if book['pages'] > min_pages.
4
Create Flask route to display filtered books
Import Flask and create an app. Then add a route /books that returns a string with the titles of filtered_books joined by commas
Flask
Hint
Import Flask, create app, define route /books, and return joined titles.
Practice
(1/5)
1. What is the main benefit of using query filters in Flask SQLAlchemy?
easy
A. To increase the number of database connections
B. To slow down the query execution
C. To make the database schema more complex
D. To reduce the amount of data retrieved from the database
Solution
Step 1: Understand query filters
Query filters limit the rows returned by a database query based on conditions.
Step 2: Effect on data retrieval
By filtering, only relevant data is fetched, reducing load and improving speed.
Final Answer:
To reduce the amount of data retrieved from the database -> Option D
Quick Check:
Filters reduce data load = B [OK]
Hint: Filters limit data fetched, making queries faster [OK]
Common Mistakes:
Thinking filters increase data size
Confusing filters with database schema changes
Assuming filters slow down queries
2. Which of the following is the correct syntax to limit query results to 10 records in Flask SQLAlchemy?
easy
A. User.limit(10).query.all()
B. User.query.all().limit(10)
C. User.query.limit(10).all()
D. User.query.filter(10).all()
Solution
Step 1: Identify correct method chaining
In Flask SQLAlchemy, limit() is called on the query object before all().
Step 2: Check each option
User.query.limit(10).all() correctly calls limit(10) before all(). Others misuse method order or methods.
Final Answer:
User.query.limit(10).all() -> Option C
Quick Check:
Limit before all() = C [OK]
Hint: Use limit() before all() to restrict records [OK]
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.