Bird
Raised Fist0
Djangoframework~10 mins

F expressions for field comparisons in Django - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - F expressions for field comparisons
Start Query
Use F expression
Compare model fields
Generate SQL with field references
Execute query
Return filtered results
This flow shows how Django uses F expressions to compare fields within the same model in a query.
Execution Sample
Django
from django.db.models import F

# Filter products where price > cost
Product.objects.filter(price__gt=F('cost'))
This code filters Product records where the price field is greater than the cost field using an F expression.
Execution Table
StepActionF Expression EvaluationSQL GeneratedQuery Result
1Start filter queryN/ASELECT * FROM productNo results yet
2Apply filter price__gt=F('cost')Compare price and cost fieldsSELECT * FROM product WHERE price > costQuery prepared
3Execute queryDatabase compares price and cost per rowN/AReturns products with price > cost
4EndN/AN/AFiltered queryset returned
💡 Query completes after filtering all rows where price is greater than cost
Variable Tracker
VariableStartAfter Step 2After Step 3Final
querysetAll productsFiltered by price > costExecuted queryFiltered products returned
Key Moments - 2 Insights
Why do we use F('cost') instead of just 'cost' in the filter?
Using F('cost') tells Django to compare the database field 'cost' directly, not a fixed value. See execution_table step 2 where the SQL uses price > cost.
Does the comparison happen in Python or in the database?
The comparison happens in the database as shown in execution_table step 3, where the SQL query compares fields for each row.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what SQL is generated at step 2?
ASELECT * FROM product WHERE price > 100
BSELECT * FROM product WHERE price > cost
CSELECT * FROM product WHERE price > 'cost'
DSELECT * FROM product
💡 Hint
Check the 'SQL Generated' column at step 2 in the execution_table
At which step does the database compare the fields price and cost?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Query Result' columns in execution_table step 3
If we replaced F('cost') with a fixed value 50, how would the SQL change at step 2?
ASELECT * FROM product WHERE price > 'cost'
BSELECT * FROM product WHERE price > cost
CSELECT * FROM product WHERE price > 50
DSELECT * FROM product
💡 Hint
Think about how fixed values appear in SQL compared to field references in execution_table step 2
Concept Snapshot
F expressions let you compare model fields directly in queries.
Use F('fieldname') inside filters to refer to another field.
Django generates SQL comparing columns, not fixed values.
This runs in the database for efficiency.
Example: filter(price__gt=F('cost')) finds rows where price > cost.
Full Transcript
This visual trace shows how Django's F expressions work for comparing fields in a query. First, the query starts with all products. Then, using filter(price__gt=F('cost')), Django prepares SQL that compares the price and cost columns directly. The database executes this SQL, returning only products where price is greater than cost. The key is that F('cost') tells Django to use the database field, not a fixed value. This makes the comparison efficient and dynamic. The variable 'queryset' changes from all products to the filtered set after the query runs. Understanding this flow helps beginners see how Django builds and runs queries with field comparisons.

Practice

(1/5)
1. What is the main purpose of using F expressions in Django ORM?
easy
A. To compare or update model fields directly in the database without fetching data
B. To convert query results into Python dictionaries
C. To create new database tables automatically
D. To write raw SQL queries inside Django models

Solution

  1. Step 1: Understand what F expressions do

    F expressions allow referencing model fields directly in queries without loading data into Python.
  2. Step 2: Identify the correct use case

    This lets you compare or update fields efficiently in the database, avoiding extra data transfer.
  3. Final Answer:

    To compare or update model fields directly in the database without fetching data -> Option A
  4. Quick Check:

    F expressions = direct DB field operations [OK]
Hint: F expressions work inside queries without loading data [OK]
Common Mistakes:
  • Thinking F expressions convert results to dicts
  • Confusing F expressions with migrations
  • Assuming F expressions run raw SQL
2. Which of the following is the correct syntax to filter objects where the field score is greater than the field min_score using F expressions?
easy
A. Model.objects.filter(F('score') > F('min_score'))
B. Model.objects.filter(score > F('min_score'))
C. Model.objects.filter(score__gt='min_score')
D. Model.objects.filter(score__gt=F('min_score'))

Solution

  1. Step 1: Recall correct filter syntax with F expressions

    Use field lookups like score__gt=F('min_score') to compare fields.
  2. Step 2: Check each option

    Model.objects.filter(score__gt=F('min_score')) uses correct Django ORM syntax. Model.objects.filter(score > F('min_score')) uses invalid Python syntax inside filter. Model.objects.filter(score__gt='min_score') compares to string, not field. Model.objects.filter(F('score') > F('min_score')) is invalid syntax.
  3. Final Answer:

    Model.objects.filter(score__gt=F('min_score')) -> Option D
  4. Quick Check:

    Use field lookups with F('field') [OK]
Hint: Use field lookups like __gt with F('field') [OK]
Common Mistakes:
  • Using Python operators inside filter()
  • Passing field names as strings instead of F expressions
  • Confusing field lookup syntax
3. Given the model Product with fields price and discount_price, what will this query return?
Product.objects.filter(discount_price__lt=F('price')).count()
medium
A. The total number of products in the database
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

  1. Step 1: Understand the filter condition

    The filter selects products where discount_price is less than price using an F expression.
  2. Step 2: Understand the count() method

    It returns the number of records matching the filter condition.
  3. Final Answer:

    The number of products where discount_price is less than price -> Option B
  4. 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

  1. Step 1: Check F expression syntax

    The field name inside F() must be a string, so it should be F('total_paid').
  2. Step 2: Analyze the given query

    The query uses F(total_paid) without quotes, causing a NameError or syntax error.
  3. Final Answer:

    Missing quotes around the field name in F expression -> Option A
  4. 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

  1. 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').
  2. 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.
  3. Final Answer:

    Employee.objects.update(salary=F('salary') + F('bonus')) -> Option C
  4. 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
  • Using wrong arithmetic operator