2015-07-13 74 views
6

當我試圖(通過postgresql-contrib包)來安裝unaccent Postgres的擴展,一切正常按以下:怎樣才能激活已經存在的模型unaccent擴展

# 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。

回答

11

遷移文件需要手動製作和應用。

首先,創建一個空遷移:

./manage.py makemigrations myapp --empty 

然後打開文件,並添加UnaccentExtensionoperations

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 <user_name> SUPERUSER;及其NOSUPERUSER對應。 pgAdminIII也可以做到這一點。

現在使用Django享受unaccent功能:

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