Search code examples
djangodjango-filter

Django - Use postgres unaccent with django-filters library


I have a Django app that uses postgres. I know that if i have the unaccent extension from postgres installed in the database, I can use like it's described in the docs to apply filters ignoring the accents in the words:

>>> City.objects.filter(name__unaccent="México")
['<City: Mexico>']

>>> User.objects.filter(first_name__unaccent__startswith="Jerem")
['<User: Jeremy>', '<User: Jérémy>', '<User: Jérémie>', '<User: Jeremie>']

In this app I'm also using the django-filter library. I was wondering if there is a way to use the unaccent extension in conjunction with django-filter to avoid rewriting all my search functions. Here is an example of the code used to filter:

class BranchesFilter(django_filters.FilterSet):
    name = CharFilter(
        label='Filial',
        label_suffix='',
        field_name='name',
        lookup_expr='icontains',
    )
    
    class Meta:
        model = Branches
        fields = '__all__'

Appreciate the help.


Solution

  • Replying this just in case someone has the same question. Turns out this is way simpler than i thought. By adding unaccent__ before the lookup expression (just like it's described in the docs), the extension can be used with django-filters. Here's the example provided in the question:

    class BranchesFilter(django_filters.FilterSet):
        name = CharFilter(
            label='Filial',
            label_suffix='',
            field_name='name',
            lookup_expr='unaccent__icontains',
        )
        
        class Meta:
            model = Branches
            fields = '__all__'