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
[
2
Answers
As you want to filter departments by their name so you can write params in your filter method like this
It seems there is no need to define a whole method to search by name. Try to define field
q
asThis will fix both incorrect search and case-sensitivity with cyrillic letters