Lesson 35 of 60 – Filtering Data in Django
58%

Filtering Data in Django

Filtering data means retrieving only the database records that match specific conditions. Django ORM provides the filter() method along with many lookup expressions for creating powerful database queries.

Note: The filter() method returns a QuerySet. The QuerySet can contain zero, one, or many matching records.

1. What is Filtering?

Filtering means selecting only the records that satisfy a particular condition.

For example, if a Student table contains 100 students, you may want to retrieve only students who are 18 years old.

Student.objects.filter(
    age=18
)

2. The filter() Method

The filter() method is the most commonly used method for filtering records.

students = Student.objects.filter(
    age=20
)

The result is a QuerySet containing students whose age is 20.

3. Filtering by Exact Value

You can filter records using an exact field value.

students = Student.objects.filter(
    course="Python"
)

This retrieves students whose course is exactly Python.

4. Filtering by Multiple Conditions

Multiple keyword conditions can be supplied to filter().

students = Student.objects.filter(
    age=20,
    course="Python"
)

The conditions are combined using AND behavior.

5. Filtering Boolean Fields

Boolean fields can be filtered using True or False.

students = Student.objects.filter(
    is_active=True
)

This retrieves active students.

students = Student.objects.filter(
    is_active=False
)

This retrieves inactive students.

6. Filtering with __gt

The __gt lookup means greater than.

students = Student.objects.filter(
    age__gt=18
)

This retrieves students whose age is greater than 18.

7. Filtering with __gte

The __gte lookup means greater than or equal to.

students = Student.objects.filter(
    age__gte=18
)

This retrieves students aged 18 or older.

8. Filtering with __lt

The __lt lookup means less than.

students = Student.objects.filter(
    age__lt=18
)

This retrieves students younger than 18.

9. Filtering with __lte

The __lte lookup means less than or equal to.

students = Student.objects.filter(
    age__lte=18
)

This retrieves students whose age is 18 or less.

10. Filtering with __contains

The __contains lookup searches for values containing a specific sequence of characters.

students = Student.objects.filter(
    name__contains="Rah"
)

This can find names containing the specified text.

11. Filtering with __icontains

The __icontains lookup performs a case-insensitive containment search.

students = Student.objects.filter(
    name__icontains="rahul"
)

This can match names such as Rahul without requiring the same letter case.

12. Filtering with __startswith

The __startswith lookup finds values beginning with the specified text.

students = Student.objects.filter(
    name__startswith="A"
)

This can be useful for searching names by their first characters.

13. Filtering with __istartswith

The __istartswith lookup performs a case-insensitive starts-with search.

students = Student.objects.filter(
    name__istartswith="rah"
)

This can match names beginning with Rahul, rahul, or another case variation, subject to database behavior.

14. Filtering with __endswith

The __endswith lookup finds values ending with specified text.

students = Student.objects.filter(
    name__endswith="Kumar"
)

This retrieves records whose name ends with Kumar.

15. Filtering with __iendswith

The __iendswith lookup performs a case-insensitive ends-with search.

students = Student.objects.filter(
    name__iendswith="kumar"
)

This can match different letter-case variations of the ending text.

16. Filtering with __in

The __in lookup checks whether a field value exists in a specified list.

students = Student.objects.filter(
    age__in=[18, 20, 22]
)

This retrieves students whose age is 18, 20, or 22.

17. Filtering with __range

The __range lookup can be used to filter values within a range.

students = Student.objects.filter(
    age__range=(18, 25)
)

This retrieves records whose age falls within the specified range.

18. Filtering NULL Values

The isnull lookup can be used to find fields containing NULL.

students = Student.objects.filter(
    phone__isnull=True
)

This retrieves records where the phone field is NULL.

students = Student.objects.filter(
    phone__isnull=False
)

This retrieves records where the phone field is not NULL.

19. Filtering Date Fields

Date fields can also be filtered using lookup expressions.

students = Student.objects.filter(
    admission_date__year=2026
)

You can also filter by month:

students = Student.objects.filter(
    admission_date__month=9
)

20. Filtering Date Ranges

A date field can be filtered using a range of dates.

students = Student.objects.filter(
    admission_date__range=[
        "2026-01-01",
        "2026-12-31"
    ]
)

This can be useful for reports and date-based searches.

21. Filtering with exclude()

The exclude() method returns records that do not match the specified condition.

students = Student.objects.exclude(
    course="Python"
)

This retrieves students whose course is not Python.

22. Combining filter() and exclude()

You can combine QuerySet methods to create more specific queries.

students = Student.objects.filter(
    is_active=True
).exclude(
    course="Python"
)

This retrieves active students who are not enrolled in Python.

23. Filtering with OR Conditions

Django's Q objects can be used when you need OR conditions.

from django.db.models import Q

students = Student.objects.filter(
    Q(course="Python") |
    Q(course="Django")
)

The pipe symbol | represents OR between the two conditions.

24. Using AND with Q Objects

The & operator can be used with Q objects to combine conditions using AND logic.

students = Student.objects.filter(
    Q(age__gte=18) &
    Q(is_active=True)
)

This retrieves students who are at least 18 and active.

25. Negating a Q Condition

The ~ operator can be used to negate a Q condition.

students = Student.objects.filter(
    ~Q(course="Python")
)

This retrieves records where the course condition is not Python.

26. Filtering Related Models

Django can filter records using fields from related models with double underscores.

students = Student.objects.filter(
    course__name="Python"
)

If course is a ForeignKey to a Course model, this retrieves students whose related course has the name Python.

27. Filtering from a Search Form

A search keyword can be received from the URL and used to filter records.

keyword = request.GET.get(
    "q",
    ""
)

students = Student.objects.filter(
    name__icontains=keyword
)

This is a common pattern for implementing search functionality.

28. Chaining Filters

Several filtering operations can be chained together.

students = Student.objects.filter(
    age__gte=18
).filter(
    is_active=True
).filter(
    name__icontains="rah"
)

The resulting QuerySet contains records satisfying all these conditions.

29. Common Filtering Mistakes

  • Using the wrong model field name.
  • Forgetting the double underscore in lookup expressions.
  • Using get() when multiple records may match.
  • Forgetting that filter() returns a QuerySet.
  • Using contains when a case-insensitive search is required.
  • Not checking whether the QuerySet contains any records.
  • Using a very broad search condition unintentionally.
  • Forgetting to import Q when using Q objects.
  • Not testing complex filtering conditions carefully.

30. Summary of Filtering Data

Django ORM provides many lookup expressions and QuerySet methods for filtering database records.

  • filter() retrieves matching records.
  • exclude() excludes matching records.
  • __gt means greater than.
  • __gte means greater than or equal to.
  • __lt means less than.
  • __lte means less than or equal to.
  • __contains searches for contained text.
  • __icontains performs a case-insensitive containment search.
  • __startswith searches for a starting value.
  • __endswith searches for an ending value.
  • __in checks values against a list.
  • __range filters values within a range.
  • isnull checks NULL values.
  • Q objects allow complex AND, OR, and NOT conditions.
  • Double underscores can be used to filter related model fields.

📌 Key Points

  • filter() is used to retrieve matching records.
  • Multiple conditions can be passed to filter().
  • Django provides many lookup expressions for text and numeric fields.
  • __icontains is useful for case-insensitive text searching.
  • __in checks whether a value exists in a list.
  • __range can be used for range-based filtering.
  • isnull can be used to check NULL values.
  • exclude() can remove unwanted conditions from the result.
  • Q objects are useful for complex OR and NOT conditions.
  • Related models can be filtered using double-underscore lookups.

🧠 Quick Quiz

Question: Which Django ORM method is used to retrieve records that match specified conditions?