0

Is there a way in Django to filter some CharField/TextField using string containing only ASCII characters but matching records in the database that may contain non-ASCII characters?

eg. I would like below code to find a city with name set to Köln:

from django.db import models

class City(models.Model):
    name = models.CharField(max_length=30)

City.objects.filter(name__<some lookup>='koln')
umat
  • 607
  • 1
  • 13
  • 25

1 Answers1

0

So, the answer for my question was actualy unaccent lookup since I am using PostgreSQL. Here are the docs: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/lookups/#unaccent

This lookup field does not work right off the bat, first one needs to install unaccent extension.

Credits to this answer - easy way to do that is to create empty migration and add unaccent extension with Django.

python manage.py makemigrations --empty <app_name>

Then in the new migration file:

from django.db import migrations
from django.contrib.postgres.operations import UnaccentExtension


class Migration(migrations.Migration):

    dependencies = [
        ('app_name', '<parent_migration>'),
    ]

    operations = [
        UnaccentExtension(),
    ]

Now I can do desired query like this:

City.objects.filter(name__unaccent__iexact='koln')

And it works just as expected :)

umat
  • 607
  • 1
  • 13
  • 25