Filtering QuerySets
In this page:
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.
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.
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.
qs = Book.objects.filter(genre='Action')
qs = qs.filter(pages__gt=100)
print(qs.count())
⚠️ Run this command in your terminal.
- Using .get() when multiple rows could match, instead of .filter(), which raises MultipleObjectsReturned.
- Chaining unrelated conditions across separate .filter() calls when a single combined filter would be clearer and faster.
- Filtering in Python after fetching everything with .all(), instead of letting the database do the filtering with .filter().
- .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.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: