0
0
Djangoframework~30 mins

F expressions for field comparisons in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
F expressions for field comparisons
📖 Scenario: You are building a Django app to manage a bookstore. You want to find all books where the number of copies sold is greater than the number of copies in stock.
🎯 Goal: Create a Django query using F expressions to compare two fields in the Book model and filter books where copies_sold is greater than copies_in_stock.
📋 What You'll Learn
Create a Django model called Book with fields title (CharField), copies_sold (IntegerField), and copies_in_stock (IntegerField).
Create a variable threshold set to 0 (to use later).
Use Django's F expression to filter Book objects where copies_sold is greater than copies_in_stock.
Assign the filtered queryset to a variable called books_sold_more_than_stock.
💡 Why This Matters
🌍 Real World
Comparing fields in database records is common in apps like inventory management, sales tracking, and more.
💼 Career
Understanding F expressions helps you write efficient database queries in Django, a key skill for backend developers.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with fields: title as a CharField with max length 100, copies_sold as an IntegerField, and copies_in_stock as an IntegerField.
Django
Need a hint?

Use models.CharField for text and models.IntegerField for numbers.

2
Add a threshold variable
Create a variable called threshold and set it to 0.
Django
Need a hint?

Just assign 0 to a variable named threshold.

3
Filter books using F expressions
Import F from django.db.models. Use Book.objects.filter() with an F expression to filter books where copies_sold is greater than copies_in_stock. Assign the result to books_sold_more_than_stock.
Django
Need a hint?

Use copies_sold__gt=F('copies_in_stock') inside filter().

4
Complete the Django query setup
Ensure the import of F from django.db.models is present and the variable books_sold_more_than_stock holds the filtered queryset where copies_sold is greater than copies_in_stock.
Django
Need a hint?

Check that the import and filter line are exactly as specified.