Search code examples
djangodjango-rest-frameworkdjango-filter

Search with or without space in django filter


I have a search by name function, which should return the name of one person if the search matches the name.I need to show results with or without space between them. Eg: ‘A B C’ should show results A B Chacko, AB Chacko, AB Chaks etc. similarly, the search The term ‘ABC’ needs also list the above results.

try:
    term = request.GET['term']
    if term:
            queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains =term)|Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
    else:
        pass
except:
    pass

The models only have the 'name ' field not have first name, last name


Solution

  • Try this code but this is very bad for performance.

        try:
            term = request.GET['term']
            if term:
                    queryset_primary = PrimaryUserSerializer(UserTable.objects.filter(Q(name__icontains =term) | Q(name__istartswith=term) | Q(name__iexact=term) | Q(name__iendswith=term) | Q(name__startswith=trm)| Q(occupation__icontains=term)).order_by('name'), many=True, context=context).data
            else:
                pass
    
    except:
        pass