How to implement my own search filter – Django?

I have a Book model:

class Book(models.Model):
    title = models.CharField()
    ...

HTML form:

<form type="get" action=".">
    <input id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button type="submit" >Submit</button>
</form>

For example:
User input some text in my form:"Some strange text"
I wanna find all books, which contain at least one of these words in upper or lower case or some phrases in this text(‘Some’, ‘some’, ‘Strange’, ‘strange’, ‘Text’, ‘text’ or ‘some strange’, ‘Strange text’ and so on).
How can I do that?

>Solution :

You can split the search query to obtain the words, and then match these with the title of the book. We can do this by constructing a Q object [Django-doc] that will represent the filter condition:

from django.db.models import Q

query = request.GET.get('search_box')
books = Book.objects.all()
if query:
    query = query.split()
    q_obj = Q(
        *[Q(('title__icontains', item)) for item in query],
        _connector=Q.OR
    )
    books = Book.objects.filter(q_obj)

If the search box is filled in, it will filter the books queryset, such that it contains at least one word of the query.

Leave a Reply