Filters in Django

What are Filters in Django?

Django-filter is a tool that helps make it easier to filter data in Django applications. It automatically creates forms that allow users to filter records based on model fields. This saves developers time by handling the repetitive task of writing filter logic for views.

Filter Use Case

Imagine shopping for a mobile phone online without filters—you'd have to scroll through countless products. With filters, you can quickly select the "Mobile Phones" category, set a "Price Range" and choose a "Brand" instantly showing only the products that match. It saves time and makes shopping much easier.

What are Template Filters?

Template filters in Django are used to modify or format variable values in templates. They are applied using the pipe symbol |, allowing you to manipulate data before displaying it — like converting text to uppercase or formatting dates.

Built-in Template Filter Examples:

lower: Converts the string to lowercase.

upper: Converts the string to uppercase.

length: Returns the length of the string or list.

truncatechars: Truncates a string to the specified number of characters.

date: Formats a date according to the given format.

default: Returns the default value if the variable is empty.

default_if_none: Returns the default value if the variable is `None`.

escape: Escapes HTML entities in the string.

linebreaks: Converts newlines to p and br HTML tags.

join: Joins a list of items into a string with a separator.

time: Formats a time object as per the specified format.

urlencode: Escapes a string for use in a URL.

Template Filter Examples
# Filter Data on an HTML Page Using Template Filters
{{ user.name|upper }}   # Output: ABHI
{{ user.dob|date:"d-m-Y" }}   # Output: 25-04-1998
{{ date|time:"H:i" }}   # Output: 14:30
{{ text|truncatechars:10 }}   # Output: This is a
{{ value|default:"Not Available" }}   # Output: Not Available
{{ iterable|join:", " }}   # Output: item1, item2, item3

Custom Template Filter

A custom template filter in Django allows you to create your own filters to manipulate data in templates. It is defined in a Python function and registered using the @register.filter decorator.

Custom Filter Example
# Structure of a Custom Template Filter
project/
├── your_app/
│   ├── views.py
│   ├── models.py
│   ├── templates
│   └── templatetags/
│       ├── __init__.py
│       └── custom_filters.py
                    
# your_app/templatetags/custom_filters.py
from django import template

register = template.Library()

@register.filter(name='reverse_string')
def reverse_string(value):
    return value[::-1]

# Use it in a HTML page 
{% load custom_filters %}
Reversed name: {{ name|reverse_string }}

QuerySet Filters in Django

QuerySet filters are used to retrieve specific data from the database using conditions. They are applied using the .filter() method on a model's QuerySet to narrow down results, like filtering users by status etc.

QuerySet Filter Examples
from django.db.models import Q
from .models import Employee

# Single filter with multiple conditions
developers = Employee.objects.filter(role='Developer', is_active=True)

# Chained filters
developers = Employee.objects.filter(role='Developer').filter(is_active=True)

# Get all employees who are NOT developers
non_developers = Employee.objects.exclude(role='Developer')

# Get all employees who are NOT Tester
non_devs = Employee.objects.filter(~Q(role='Tester'))

# Get all active developers OR designers
employees = Employee.objects.filter(
    Q(role='Developer') | Q(role='Designer'),
    is_active=True
)

Advanced QuerySet Filters in Django

These filters help apply specific conditions in Django ORM to retrieve precise data, including exact matches, ranges, null checks, and substring searches.

Advanced QuerySet Filters:

exact: Matches the exact value (case-sensitive).

iexact: Matches the exact value (case-insensitive).

icontains: Performs a case-insensitive substring match.

startswith: Checks if the string begins with a specified substring.

lte: Filters records where the value is less than or equal to the specified number.

gte: Filters records where the value is greater than or equal to the specified number.

in: Filters records where the field value is within the provided list.

isnull: Checks if the field is NULL (i.e., has no value).

range: Value is between a specified minimum and maximum range (inclusive).

Advanced Filter Examples
# exact: Matches the exact value (case-sensitive)
Employee.objects.filter(role__exact='Developer')

# iexact: Matches the exact value (case-insensitive)
Employee.objects.filter(name__iexact='developer')

# icontains: Case-insensitive match (e.g., "dev" will match "Developer")
Employee.objects.filter(role__icontains='dev')

# startswith: Checks if role starts with 'Dev'
Employee.objects.filter(role__startswith='Dev')

# lte: Less than or equal to (e.g., age <= 30)
Employee.objects.filter(age__lte=30)

# gte: Greater than or equal to (e.g., salary >= 50000)
Employee.objects.filter(salary__gte=50000)

# in: Field value in a given list
Employee.objects.filter(department__in=['HR', 'Sales', 'IT'])

# isnull: Check if a field is NULL (e.g., no manager assigned)
Employee.objects.filter(manager__isnull=True)

# range: Value is between 25 and 35 (inclusive).
Employee.objects.filter(age__range=(25, 35))

Exercise

  1. Fill in the Blanks:
    • - To filter records based on conditions in a Django QuerySet, you use the __________ method.
    • - The __________ decorator is used to create a custom template filter in Django.
    • - The __________ filter performs a case-insensitive substring match on a field value.
    • - The filter checks if a string field starts with a specified substring: __________.
    • - The filter is used to match values exactly (case-sensitive) in a QuerySet: __________.