B. The number of products where discount_price is less than price
C. The number of products where discount_price equals price
D. Raises a syntax error
Solution
Step 1: Understand the filter condition
The filter selects products where discount_price is less than price using an F expression.
Step 2: Understand the count() method
It returns the number of records matching the filter condition.
Final Answer:
The number of products where discount_price is less than price -> Option B
Quick Check:
filter with F expression returns matching count [OK]
Hint: F expressions compare fields inside filters correctly [OK]
Common Mistakes:
Thinking count() returns all products
Confusing less than with equals
Assuming syntax error due to F expression
4. Identify the error in this Django query using F expressions:
Order.objects.filter(total__gt=F(total_paid))
medium
A. Missing quotes around the field name in F expression
B. Using __gt instead of __lt for comparison
C. F expressions cannot be used in filters
D. total and total_paid fields must be integers
Solution
Step 1: Check F expression syntax
The field name inside F() must be a string, so it should be F('total_paid').
Step 2: Analyze the given query
The query uses F(total_paid) without quotes, causing a NameError or syntax error.
Final Answer:
Missing quotes around the field name in F expression -> Option A
Quick Check:
F('field_name') requires quotes [OK]
Hint: Always put field names as strings inside F() [OK]
Common Mistakes:
Omitting quotes inside F()
Confusing comparison operators
Believing F expressions can't be in filters
5. You want to update all Employee records to increase their salary by the value in their bonus field using F expressions. Which code snippet correctly performs this update?
hard
A. Employee.objects.update(salary=F('salary' + 'bonus'))
B. Employee.objects.update(salary='salary + bonus')
C. Employee.objects.update(salary=F('salary') + F('bonus'))
D. Employee.objects.update(salary=F('salary') - F('bonus'))
Solution
Step 1: Understand how to update fields with F expressions
You can perform arithmetic operations between fields using F expressions like F('salary') + F('bonus').
Step 2: Check each option
Employee.objects.update(salary=F('salary') + F('bonus')) correctly adds the two fields. Employee.objects.update(salary=F('salary' + 'bonus')) incorrectly concatenates strings inside F(). Employee.objects.update(salary='salary + bonus') assigns a string, not a field operation. Employee.objects.update(salary=F('salary') - F('bonus')) subtracts instead of adding.
Final Answer:
Employee.objects.update(salary=F('salary') + F('bonus')) -> Option C
Quick Check:
Use arithmetic with F('field') for updates [OK]
Hint: Use F('field1') + F('field2') for field arithmetic updates [OK]
Common Mistakes:
Concatenating field names as strings inside F()
Assigning string expressions instead of F expressions