How to Use filter() in Django ORM for Querying Data
Use Django ORM's
filter() method on a model's manager to get records matching specific conditions. It returns a QuerySet of objects that meet the criteria, allowing you to chain multiple filters for precise queries.Syntax
The filter() method is called on a Django model's manager (usually objects) and accepts keyword arguments representing field lookups. Each argument filters the records where the field matches the given value or condition.
Model.objects.filter(field=value): Returns records wherefieldequalsvalue.- Supports lookups like
field__lt,field__contains, etc., for more complex filters. - Returns a
QuerySetthat can be further filtered or iterated.
python
Model.objects.filter(field=value) Model.objects.filter(field__lookup=value) # Example: Book.objects.filter(author='Alice') Book.objects.filter(pages__gt=100)
Example
This example shows how to use filter() to get all books by author 'Alice' with more than 100 pages.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) pages = models.IntegerField() # Query to get books by author 'Alice' with pages greater than 100 books = Book.objects.filter(author='Alice', pages__gt=100) for book in books: print(f"{book.title} by {book.author}, {book.pages} pages")
Output
The Great Adventure by Alice, 150 pages
Mystery Tales by Alice, 120 pages
Common Pitfalls
Common mistakes when using filter() include:
- Using
filter()when you want a single object; useget()instead. - Not using double underscores
__for lookups likegt(greater than),contains, etc. - Forgetting that
filter()returns a QuerySet, which can be empty but won't raise errors. - Using incorrect field names or misspelling them causes errors.
Wrong: Book.objects.filter(author='Alice', pages>100) (syntax error)
Right: Book.objects.filter(author='Alice', pages__gt=100)
python
wrong_books = Book.objects.filter(author='Alice', pages>100) # SyntaxError right_books = Book.objects.filter(author='Alice', pages__gt=100) # Correct usage
Quick Reference
| Lookup | Description | Example |
|---|---|---|
| exact | Field equals value | filter(name__exact='John') |
| iexact | Case-insensitive exact match | filter(name__iexact='john') |
| contains | Field contains substring | filter(title__contains='Django') |
| icontains | Case-insensitive contains | filter(title__icontains='django') |
| gt | Greater than | filter(age__gt=18) |
| gte | Greater than or equal | filter(age__gte=18) |
| lt | Less than | filter(price__lt=100) |
| lte | Less than or equal | filter(price__lte=100) |
| startswith | Starts with substring | filter(name__startswith='A') |
| istartswith | Case-insensitive starts with | filter(name__istartswith='a') |
| endswith | Ends with substring | filter(email__endswith='.com') |
| iendswith | Case-insensitive ends with | filter(email__iendswith='.com') |
Key Takeaways
Use
filter() to get QuerySets matching conditions on model fields.Chain multiple filters by passing multiple keyword arguments to narrow results.
Use double underscores
__ for field lookups like gt, contains, etc.Remember
filter() returns zero or more records; use get() for a single record.Check field names carefully to avoid errors when filtering.