0
0
DjangoHow-ToBeginner · 4 min read

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 where field equals value.
  • Supports lookups like field__lt, field__contains, etc., for more complex filters.
  • Returns a QuerySet that 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; use get() instead.
  • Not using double underscores __ for lookups like gt (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

LookupDescriptionExample
exactField equals valuefilter(name__exact='John')
iexactCase-insensitive exact matchfilter(name__iexact='john')
containsField contains substringfilter(title__contains='Django')
icontainsCase-insensitive containsfilter(title__icontains='django')
gtGreater thanfilter(age__gt=18)
gteGreater than or equalfilter(age__gte=18)
ltLess thanfilter(price__lt=100)
lteLess than or equalfilter(price__lte=100)
startswithStarts with substringfilter(name__startswith='A')
istartswithCase-insensitive starts withfilter(name__istartswith='a')
endswithEnds with substringfilter(email__endswith='.com')
iendswithCase-insensitive ends withfilter(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.