skip to Main Content

I’m trying to create search for my project with postgres.search. And it works but works incorrect. It works too precisely. For example: When I’m searching bolu, nothing is found. But when I’m searching bolum it founds. How can I fix it?

# filters.py

class DepartmentFilter(filters.FilterSet):
    branch = filters.CharFilter(field_name="branches__id", lookup_expr="in")
    q = filters.CharFilter(method="search_filter")

    def search_filter(self, queryset, _, value):
        search_vector = SearchVector("name")
        search_query = SearchQuery(value)
        return (
            queryset.annotate(search=search_vector)
            .filter(search=search_query)
        )

    class Meta:
        model = Department
        fields = ["branch", "q"]


# models.py

class Branch(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Branches"

    def __str__(self):
        return self.name


class Department(models.Model):
    name = models.CharField(max_length=100)
    branches = models.ManyToManyField(Branch, related_name="department")

    def __str__(self):
        return self.name
[Not Works

Works

2

Answers


  1. As you want to filter departments by their name so you can write params in your filter method like this

    .filter(name__icontains=search_query)
    
    Login or Signup to reply.
  2. It seems there is no need to define a whole method to search by name. Try to define field q as

    q = filters.CharFilter(field_name="name", lookup_expr="icontains")
    

    This will fix both incorrect search and case-sensitivity with cyrillic letters

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search