Bird
Raised Fist0
Djangoframework~30 mins

Field lookups (exact, contains, gt, lt) in Django - Mini Project: Build & Apply

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
Filtering Django QuerySets with Field Lookups
📖 Scenario: You are building a simple Django app to manage a bookstore's inventory. You want to filter books based on different criteria like exact title, partial author name, price greater than a value, and publication year less than a value.
🎯 Goal: Learn how to use Django ORM field lookups exact, contains, gt, and lt to filter QuerySets.
📋 What You'll Learn
Create a Django model Book with fields title, author, price, and year_published
Create a QuerySet variable books with some sample book objects
Create a variable price_threshold set to 20
Filter books with exact title 'Django Basics' using exact lookup
Filter books with author name containing 'Smith' using contains lookup
Filter books with price greater than price_threshold using gt lookup
Filter books published before year 2010 using lt lookup
💡 Why This Matters
🌍 Real World
Filtering data in Django apps is essential for showing users only relevant information, like books matching their search criteria.
💼 Career
Understanding Django ORM field lookups is a key skill for backend developers working with Django to build efficient and readable database queries.
Progress0 / 4 steps
1
Create the Book model and sample data
Create a Django model class called Book with fields title (CharField), author (CharField), price (FloatField), and year_published (IntegerField). Then create a QuerySet variable called books with these exact book instances: Book(title='Django Basics', author='John Smith', price=15.99, year_published=2015), Book(title='Advanced Django', author='Jane Doe', price=25.50, year_published=2018), Book(title='Python 101', author='Mike Smith', price=19.99, year_published=2008), Book(title='Web Development', author='Anna Johnson', price=22.00, year_published=2005).
Django
Hint

Use Django model fields like CharField for text, FloatField for price, and IntegerField for year. Create a list of Book instances for books.

2
Set the price threshold variable
Create a variable called price_threshold and set it to the float value 20.0.
Django
Hint

Just create a variable named price_threshold and assign it the value 20.0.

3
Filter books using field lookups
Create four new variables to filter the books list using Django-like field lookups: exact_title for books with title exactly 'Django Basics' using exact lookup, author_contains_smith for books with author containing 'Smith' using contains lookup, price_gt_threshold for books with price greater than price_threshold using gt lookup, and year_lt_2010 for books published before 2010 using lt lookup. Use list comprehensions to simulate these filters.
Django
Hint

Use list comprehensions with conditions matching the field lookups: == for exact, in for contains, > for gt, and < for lt.

4
Complete the filtering with Django QuerySet style
Add a final line that creates a Django QuerySet-like filter call named filtered_books that chains all four filters using Django ORM syntax: filter books with title exactly 'Django Basics', author containing 'Smith', price greater than price_threshold, and year published less than 2010. Use the Django QuerySet filter() method with keyword arguments and chaining.
Django
Hint

Use Django ORM chaining with filter() and double underscores for lookups like title__exact, author__contains, price__gt, and year_published__lt.

Practice

(1/5)
1. Which Django field lookup would you use to find records where a field exactly matches a given value?
easy
A. exact
B. contains
C. gt
D. lt

Solution

  1. Step 1: Understand the purpose of each lookup

    The exact lookup matches fields that are exactly equal to the given value. contains checks for substring presence, gt means greater than, and lt means less than.
  2. Step 2: Match the requirement to the lookup

    Since the question asks for exact matches, exact is the correct lookup.
  3. Final Answer:

    exact -> Option A
  4. Quick Check:

    Exact match = exact [OK]
Hint: Exact match uses 'exact' lookup in Django queries [OK]
Common Mistakes:
  • Confusing 'contains' with exact match
  • Using 'gt' or 'lt' for equality checks
  • Assuming 'exact' is default without specifying
2. Which of the following is the correct syntax to filter a Django model Book for titles containing the word 'django'?
easy
A. Book.objects.filter(title__exact='django')
B. Book.objects.filter(title__gt='django')
C. Book.objects.filter(title__contains='django')
D. Book.objects.filter(title__lt='django')

Solution

  1. Step 1: Identify the lookup for substring matching

    The contains lookup is used to find records where the field contains the given substring anywhere inside it.
  2. Step 2: Check the syntax for filtering

    The correct syntax uses double underscores to specify the lookup: title__contains='django'.
  3. Final Answer:

    Book.objects.filter(title__contains='django') -> Option C
  4. Quick Check:

    Substring search = contains [OK]
Hint: Use __contains for substring filters in Django queries [OK]
Common Mistakes:
  • Using __exact for substring search
  • Using __gt or __lt for string matching
  • Missing double underscores in lookup
3. Given the model Product with a field price, what will this query return?
Product.objects.filter(price__gt=100)
medium
A. All products with price greater than 100
B. All products with price exactly 100
C. All products with price less than 100
D. All products with price containing '100'

Solution

  1. Step 1: Understand the lookup used

    The lookup price__gt=100 means filter products where the price is greater than 100.
  2. Step 2: Interpret the query result

    The query returns all products with price values strictly greater than 100, excluding 100 itself.
  3. Final Answer:

    All products with price greater than 100 -> Option A
  4. Quick Check:

    gt means greater than [OK]
Hint: gt means greater than in Django filters [OK]
Common Mistakes:
  • Confusing gt with exact or contains
  • Thinking gt includes the value 100
  • Assuming it filters less than 100
4. You wrote this Django query but it raises an error:
Entry.objects.filter(date__gt='2023-01-01')

What is the most likely cause?
medium
A. You must use 'exact' lookup for date filtering
B. The field 'date' is not a DateField or DateTimeField
C. The date string format is incorrect for filtering
D. The lookup 'gt' is not valid for date fields

Solution

  1. Step 1: Check field type compatibility

    The gt lookup works with fields that support ordering like DateField or DateTimeField. If date is not one of these, the query will error.
  2. Step 2: Validate other options

    The lookup gt is valid for date fields, and the string format is acceptable for Django's date parsing. Using exact is not required.
  3. Final Answer:

    The field 'date' is not a DateField or DateTimeField -> Option B
  4. Quick Check:

    gt requires comparable field type [OK]
Hint: Ensure field type supports lookup before filtering [OK]
Common Mistakes:
  • Assuming all fields support gt lookup
  • Incorrect date string format causing error
  • Using exact lookup unnecessarily
5. You want to find all Order records where the status field contains 'pending' (case insensitive) and the total is less than 500. Which Django query correctly applies these filters?
hard
A. Order.objects.filter(status__contains='pending', total__gt=500)
B. Order.objects.filter(status__contains='pending', total__lt=500)
C. Order.objects.filter(status__exact='pending', total__lt=500)
D. Order.objects.filter(status__icontains='pending', total__lt=500)

Solution

  1. Step 1: Choose case-insensitive substring lookup

    To find 'pending' regardless of case, use icontains instead of contains.
  2. Step 2: Apply less than filter on total

    The total__lt=500 filters orders with total less than 500.
  3. Step 3: Combine filters correctly

    Both filters are passed as keyword arguments to filter() to apply AND logic.
  4. Final Answer:

    Order.objects.filter(status__icontains='pending', total__lt=500) -> Option D
  5. Quick Check:

    Case-insensitive contains + less than = icontains + lt [OK]
Hint: Use icontains for case-insensitive substring filters [OK]
Common Mistakes:
  • Using contains instead of icontains for case insensitivity
  • Mixing lt and gt incorrectly
  • Using exact instead of contains for substring search