【问题标题】:How can I activate the unaccent extension on an already existing model如何在现有模型上激活非重音扩展
【发布时间】:2015-10-01 16:14:10
【问题描述】:

当我尝试安装 unaccent Postgres 扩展(通过 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)

但是,当我尝试使用 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.

使用 Postgresql 9.3 和 Django 1.8。

【问题讨论】:

    标签: django postgresql django-models


    【解决方案1】:

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

    首先,创建一个空迁移:

    ./manage.py makemigrations myapp --empty
    

    然后打开文件,将UnaccentExtension添加到operations

    from django.contrib.postgres.operations import UnaccentExtension
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            (<snip>)
        ]
    
        operations = [
            UnaccentExtension()
        ]
    

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

    如果您在最后一步出现以下错误:

    django.db.utils.ProgrammingError: permission denied to create extension "unaccent"
    HINT:  Must be superuser to create this extension.
    

    ...然后通过执行postgres# ALTER ROLE &lt;user_name&gt; SUPERUSER; 及其NOSUPERUSER 对应项来临时允许您的用户拥有超级用户权限。 pgAdminIII 也可以做到这一点。

    现在享受使用 Django 的非重音功能:

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

    【讨论】:

    • 祝福你,古人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2021-06-28
    • 1970-01-01
    • 2012-05-20
    相关资源
    最近更新 更多