Challenge - 5 Problems
F Expressions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What does this Django query return?
Consider a Django model
Product with fields price and discount_price. What does this query return?Product.objects.filter(price__gt=F('discount_price'))Attempts:
2 left
💡 Hint
Remember that
F('discount_price') refers to the value of the discount_price field in the database.✗ Incorrect
The filter uses an F expression to compare the price field to the discount_price field for each product. It returns products where price is greater than discount_price.
📝 Syntax
intermediate2:00remaining
Which option correctly uses an F expression to find records where two fields are equal?
You want to find all
Order objects where total_price equals amount_paid. Which query is correct?Attempts:
2 left
💡 Hint
Use the correct Django ORM syntax for field comparisons with F expressions.
✗ Incorrect
Option A correctly uses the Django ORM syntax to compare two fields using an F expression. Option A uses an invalid lookup, C uses Python syntax not supported in filters, and D compares to a variable, not a field.
🔧 Debug
advanced2:00remaining
Why does this Django query raise an error?
Given the model
Employee with fields salary and bonus, what causes the error in this query?Employee.objects.filter(salary > F('bonus'))Attempts:
2 left
💡 Hint
Check how Django expects comparisons in filter arguments.
✗ Incorrect
Django ORM filters require lookups like __gt for greater than comparisons. Using > directly causes a syntax error.
❓ state_output
advanced2:00remaining
What is the result count of this query?
Assume the
What does this query return?
Book model has fields pages and read_pages. Which query returns books where pages are at least twice the read_pages?Book.objects.filter(pages__gte=F('read_pages') * 2)What does this query return?
Attempts:
2 left
💡 Hint
Remember that __gte means greater than or equal to.
✗ Incorrect
The filter uses an F expression with multiplication to compare pages to twice read_pages, returning books where pages >= 2 * read_pages.
🧠 Conceptual
expert3:00remaining
What happens when you use F expressions in update() with field comparisons?
Consider this code:
What is the effect of this update?
Product.objects.filter(stock__lt=F('reorder_level')).update(stock=F('stock') + 10)What is the effect of this update?
Attempts:
2 left
💡 Hint
Think about how update() and F expressions work together in Django.
✗ Incorrect
The update uses an F expression to add 10 to the stock field only for products where stock is less than reorder_level, modifying those records in the database.