← Back to Django Course | Chapter 4: Models & Django ORM Basics | Lesson 6 of 10

Filtering QuerySets

Filtering is like telling the filing cabinet 'only show me the cards where the name starts with A', instead of dumping every card on the table.

Basic Filtering

Model.objects.filter(field=value) returns only the rows where that field matches the given value, as a new QuerySet.

Example: Basic Filtering

Model.objects.filter(field=value) returns only the rows where that field matches the given value, as a new QuerySet.

bash
action_books = Book.objects.filter(genre='Action')
for book in action_books:
    print(book.title)

⚠️ Run this command in your terminal.

Filtering on Multiple Fields

Passing multiple keyword arguments to .filter() combines them with AND logic — every condition must match.

Example: Filtering on Multiple Fields

Passing multiple keyword arguments to .filter() combines them with AND logic — every condition must match.

bash
books = Book.objects.filter(genre='Action', pages__gt=100)
for book in books:
    print(book.title, book.pages)

⚠️ Run this command in your terminal.

Chaining Filters

Because .filter() returns a QuerySet, you can call .filter() again on the result to add more conditions step by step.

Example: Chaining Filters

Because .filter() returns a QuerySet, you can call .filter() again on the result to add more conditions step by step.

bash
qs = Book.objects.filter(genre='Action')
qs = qs.filter(pages__gt=100)
print(qs.count())

⚠️ Run this command in your terminal.

Common Mistakes
  1. Using .get() when multiple rows could match, instead of .filter(), which raises MultipleObjectsReturned.
  2. Chaining unrelated conditions across separate .filter() calls when a single combined filter would be clearer and faster.
  3. Filtering in Python after fetching everything with .all(), instead of letting the database do the filtering with .filter().
Chapter Summary
  • .filter(field=value) returns a QuerySet containing only the rows that match the condition.
  • You can filter on multiple fields at once by passing several keyword arguments.
  • Filtering happens in the database, which is far more efficient than filtering in Python.
  • Filters can be chained together to progressively narrow down a QuerySet.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.