How Searching is Done in Django🔍?

In this article, I’ll explain how to make a search bar in Django which performs a search on the Django database and provides the result.

Prajakta Mane
GDSC DYPCOE
Published in
3 min readMay 5, 2020

--

In order to perform search functionality in Django, we need to perform a query on the model database which is similar to any SQL query we perform.

To perform a query on database Django provides Q objects which can be imported from django.db.models.

In short Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code for more on Q objects.

Let’s get started :

Here is what models.py look like :

We have a model blog with attributes blog_author ,blog_topic and pages the thing to remember is that each attribute of a model represents a database field. So, we have a database-table blog with the column as an attribute of the model.

Problem: We want to build a simple search feature which will search for a blog entry in the blog model database based on the author of blog or topic of blog or pages in the blog.

Solution:

  1. First, we will look at our template file index.html. How it will send a request to blogSearch function in views.py to look for whether the searched field is in our database if yes than render it and if not display a not found message.
  • To reference data when a form is submitted name field of input tag is used. So, here name= “srch” will store the data for which search is made.
  • After submitting the form as the method is POST and action /blogSearch/ it will refer to blogSearch in views.py which perform the functionality of searching.

2. Second our views.py it contains blogSearch .

How blogSearch works?:

  1. It checks for request first if it is ‘POST’:
  • Then it stores data referenced by name field of input tag to search variable.
  • If it is not null it will perform query and store result in a match .
match=Blog.objects.filter(Q(blog_author__icontains=search)|Q(blog_topic__icontains=search)|Q(pages__icontains=search))equivalent SQL:
SELECT * from blogs where
blog_author LIKE '%search%' OR blog_topic LIKE '%search%' OR
pages LIKE '%search%';

__icontaing is not in new Django documentation refer this for more

  • If query or search is successful than objects which match are rendered to index.html
  • else error message is returned to index.html

2. For any other failure, we will be returned back to the same page.

How the final page will look:

index.html home page
Result of search - c++
No result found when entered the wrong field

Yeah! It’s working as expected 😍 Thus we’ve successfully implemented searching in Django! 🚀

You can find source code below:

If you found this article helpful then please share it with everyone. Maybe it’ll be helpful for someone needy!

Sharing is Caring!

Thank you! 😃

--

--