Python

How to Filter Data in Django?

It is a very common requirement for the web application to display data on the web page based on the user’s interest. The searching feature of the application makes it more user-friendly.  Django framework has a built-in filter() method to filter data from the database tables. A table can contain many records and sometimes determining some specific data are required based on the particular criteria. This task becomes easier by using the filter() method in different ways. How the data from a database table can be filtered using the filter method in four different ways will be discussed in this tutorial.

Prerequisites

Before practicing the examples of this tutorial, you must complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django App

A. Run the following command to create a Django app named filterapp.

$ python3 manage.py startapp filterapp

B. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.

$ python3 manage.py createsuperuser

C. Add the app name in the INSTALLED_APP part of the py file.

INSTALLED_APPS = [
    …..
    'filterapp'
]

D. Create a folder named templates inside the filterapp folder and set the template’s location of the app in the TEMPLATES part of the py file.

TEMPLATES = [
    {
….
            'DIRS': ['/home/fahmida/django_pro/filterapp/templates'],
             ….
      },
]

Create a Model for the Database Table

Open the models.py file from the filterapp folder and add the following script to define the structure of employees tables. Employee class is defined to create a table named employees with name, post, email, department, and joining_date fields. Here, name, post, and department fields will store character data, the email field will store the email address and the joining_date field will store date data.

models.py

# Import models module
from django.db import models

# Define class to create employees table
class Employee(models.Model):
    name = models.CharField(max_length=50)
    post = models.CharField(max_length=40)
    email = models.EmailField()
    department = models.CharField(max_length=30)
    joinning_date = models.DateField()

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations filterapp

Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Employee class of the models is registered using the register() method to display the records of employees tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import Employee model
from .models import Employee

# Register employee model
admin.site.register(Employee)

Run the following URL to open the Django admin login page. Provide the valid username and password to open the Django Administration Dashboard to access the database tables.

Insert two or more Employee records to apply the filter on the data. Here five records are inserted.

Create the search.html file inside the filterapp/templates/ folder with the following script. The data from the employee table will be displayed in this template file. for loop is used to read the content of the object_list variable that will be passed from the view file. The name, post, and department values of the employees table will be displayed by using the list.

search.html

    <title>
        Django Filter Tutorial
    </title>




<h1 style="margin-left:20px">Employee List</h1>

<ol>
  {% for emp in object_list %}
    <li>
        <p style="font-size:20px"><b>{{ emp.name }}</b> ({{ emp.post }})</p>
        <p style="font-size:18px">{{ emp.department }} department</p>
    </li>
  {% endfor %}
</ol>

Open the views.py file from the filterapp folder and modify the content of the file with the following script. Model and template names are defined in the script.

views.py

# Import ListView module
from django.views.generic import ListView
# Import Employee module
from .models import Employee
# Import Q module
from django.db.models import Q

# Define class for filtering data
class SearchEmployee(ListView):
    # Define model
    model = Employee
    # Define template
    template_name = 'search.html'

Modify the content of the urls.py file with the following content. In the script, the ‘searchEmp’ path is defined to call the SearchEmployee.as_view() method that will send all data and the filtered data of the employees table to the template file.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path, include
# Import SearchEmployee module
from filterapp.views import SearchEmployee

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
    # Define the path for search
    path('searchEmp/', SearchEmployee.as_view()),
]

The following output will appear without applying any filtering for the following URL.

http://localhost:8000/SerachEmp

Filter Data by Simple Filtering

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Accountant’.

# Apply basic filtering
queryset = Employee.objects.filter(post ='Accountant')

The following output will appear after applying basic filtering.

Filter Data with Multiple Fields

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field is ‘HT’ and the email field is [email protected].

# Apply filtering with multiple fields
queryset = Employee.objects.filter(department='HR', email='[email protected]')

The following output will appear after applying multiple filtering.

Filter Data with Q Object

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Manager’ or the value of the department field is ‘Sales’.

# Apply filtering by using Q objects
queryset = Employee.objects.filter( Q(post='Manager') | Q(department='Sales'))

The following output will appear after applying Q object filtering.

Filter Data by Using Filter Chaining

Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field will be checked first and if it returns true then the value of the name field will be checked.

# Apply filtering by chaining
queryset = Employee.objects.filter(department='HR').filter(name='Mehrab Hossain')

The following output will appear after applying filter chaining.

Conclusion

The data can be filtered in Django in many ways based on the application requirements. Four different ways of filtering were explained in this tutorial to understand the basics of Django filtering. These are simple filtering, multiple filtering, filtering with Q object, and filter chaining.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.