Performance: F expressions for field comparisons
MEDIUM IMPACT
This affects database query efficiency and reduces server load by performing comparisons directly in the database.
from django.db.models import F MyModel.objects.filter(field1__gt=F('field2')) # Correct: comparison done in database
queryset = MyModel.objects.all() filtered = [obj for obj in queryset if obj.field1 > obj.field2] # Bad: fetches all records and compares fields in Python
| Pattern | Database Load | Network Transfer | Server CPU | Verdict |
|---|---|---|---|---|
| Comparing fields in Python after fetching | Low (simple query) | High (all data fetched) | High (field comparison in Python) | [X] Bad |
| Using F expressions for field comparison | Higher (complex query) | Low (filtered data only) | Low (database does comparison) | [OK] Good |