0
0
Flaskframework~20 mins

Querying with filter and filter_by in Flask - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Filter Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Flask-SQLAlchemy query return?
Consider a model User with fields id and name. What will this query return?

users = User.query.filter(User.name == 'Alice').all()
AA single User object with name 'Alice', or None if not found.
BA list of all User objects whose name is exactly 'Alice'.
CA list of all User objects regardless of name.
DRaises a syntax error because filter needs a string argument.
Attempts:
2 left
💡 Hint
Remember that filter returns a query object that can return multiple results with .all().
📝 Syntax
intermediate
2:00remaining
Which option correctly uses filter_by to find users named 'Bob'?
Given the User model with a name field, which query correctly finds all users named 'Bob'?
AUser.query.filter_by(name='Bob').all()
BUser.query.filter_by('name' == 'Bob').all()
CUser.query.filter_by(name == 'Bob').all()
DUser.query.filter_by(name='Bob')()
Attempts:
2 left
💡 Hint
filter_by uses keyword arguments, not expressions or strings.
🔧 Debug
advanced
2:00remaining
Why does this filter query raise an error?
What error does this code raise and why?

users = User.query.filter(User.age > 20).filter_by(name='Charlie').all()
ANo error; returns users older than 20 named 'Charlie'.
BAttributeError because 'User' has no attribute 'age'.
CInvalidRequestError because mixing filter and filter_by with conflicting conditions.
DTypeError because filter_by cannot be chained after filter.
Attempts:
2 left
💡 Hint
filter and filter_by can be chained; filter_by adds keyword filters.
state_output
advanced
2:00remaining
What is the length of the result list?
Assuming the database has users with names: ['Anna', 'Bob', 'Anna', 'Charlie'], what is the length of the list returned by:

result = User.query.filter_by(name='Anna').all()
A1
B0
C3
D2
Attempts:
2 left
💡 Hint
filter_by returns all matching rows, not just one.
🧠 Conceptual
expert
2:00remaining
Which statement about filter and filter_by is true?
Choose the correct statement about the difference between filter and filter_by in Flask-SQLAlchemy.
Afilter_by accepts SQL expressions, filter accepts only keyword arguments.
BBoth filter and filter_by accept only strings as conditions.
Cfilter_by accepts keyword arguments, filter accepts SQL expressions.
Dfilter_by can be used only once per query, filter can be chained multiple times.
Attempts:
2 left
💡 Hint
Think about how you write conditions in each method.