How to ignore special characters from the search field in Django

The model is something like

class Product(BaseModel):
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)

View is

class ProductViewSet(BaseViewSet):
    queryset = Product.objects.all()
    ...
    filterset_class = ProductFilter

The filter is

class ProductFilter(django_filters.FilterSet):
    search = django_filters.CharFilter(field_name='name', lookup_expr='icontains')

    class Meta:
        model = Product
        fields = []

Now.. if the name field has a value something like "This is a/sample" and search text is "asample". I would like to return that row.

Thanks in advance.

If the question is only for one special character ie. '/' then you can create a custom filter method with Replace like this :

class ProductFilter(django_filters.FilterSet):
    def filter_without_special_chars(self, queryset, field, value):
        return queryset.annotate(search_field=Replace('name', Value('/'), Value('')).filter(search_field=value)

    search = django_filters.CharFilter(method='filter_without_special_chars')

    class Meta:
        model = Product
        fields = []

You can also do this for multiple special characters BUT it won't be the optimal solution, I would suggest you user ElasticSearch (or something similar) for that.

For multiple char replacement the function would look something like this :

def filter_without_special_chars(self, queryset, field, value):
        return queryset.annotate(sf1=Replace('name', Value('!'), Value('')),
                                 sf2=Replace('sf1', Value('%'), Value(''))).filter(sf2=value)
Back to Top