Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading