如何在现有模型上激活unaccent扩展

Sae*_*aeX 10 django postgresql django-models

当我尝试安装unaccentPostgres扩展(通过postgresql-contrib包)时,一切都按照以下方式工作:

# psql -U postgres -W -h localhost
Password for user postgres:
psql (9.3.9)
SSL connection (cipher: DHE-RSA-AES256-GCM-SHA384, bits: 256)
Type "help" for help.

postgres=# CREATE EXTENSION unaccent;
CREATE EXTENSION
postgres=# SELECT unaccent('Hélène');
 unaccent
----------
 Helene
(1 row)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用Django 1.8时,我收到以下错误:

ProgrammingError: function unaccent(character varying) does not exist
LINE 1: ...able" WHERE ("my_table"."live" = true AND UNACCENT("...
                                                             ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)

使用Postgresql 9.3和Django 1.8.

Sae*_*aeX 23

需要手动制作和应用迁移文件.

首先,创建一个空迁移:

./manage.py makemigrations myapp --empty
Run Code Online (Sandbox Code Playgroud)

然后打开文件并添加UnaccentExtensionoperations:

from django.contrib.postgres.operations import UnaccentExtension


class Migration(migrations.Migration):

    dependencies = [
        (<snip>)
    ]

    operations = [
        UnaccentExtension()
    ]
Run Code Online (Sandbox Code Playgroud)

现在使用应用迁移./manage.py migrate.

如果您在最后一步中遇到以下错误:

django.db.utils.ProgrammingError: permission denied to create extension "unaccent"
HINT:  Must be superuser to create this extension.
Run Code Online (Sandbox Code Playgroud)

...然后通过执行postgres# ALTER ROLE <user_name> SUPERUSER;及其NOSUPERUSER对应方暂时允许超级用户对您的用户的权限.pgAdminIII也可以做到这一点.

现在使用Django享受不起眼的功能:

>>> Person.objects.filter(first_name__unaccent=u"Helène")
[<Person: Michels Hélène>]
Run Code Online (Sandbox Code Playgroud)

  • 祝福你,古人。 (2认同)