'Implementing a search query inside a filter

I've been trying to implement a search bar inside my application, but I don't know how to query for similar names inside my db. Here is my view.py

    queryprms = request.GET
    name = queryprms.get('name')
    status = queryprms.get('status')
    if name:
        moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug'
    ).filter(Q(user=user), Q(name=name)).order_by("-datetime")

The problem is that when the user search for a similar word, say "Alch" for "Alchemy", the query returns empty even if "Alchemy" object exist inside my db. I want that the query returns similar objects for the user's search. How can I do that?

By the way, I'm using Postgre and Django 3.1.5.



Solution 1:[1]

For partially matching a string, you can use contains lookup keyword argument as explained in the docs. For your case, something like this could work:

PokerRoom.objects.filter(name__icontains="Alch")

Solution 2:[2]

Try this:

queryprms = request.GET
name = queryprms.get('name')
status = queryprms.get('status')
if name:
    moderatorRoom = PokerRoom.objects.values("id","first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug').filter(user=user, name__icontains=name).order_by("-datetime")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sakib Hasan
Solution 2