我有一个Postgres安装程序,设置为使用LATIN1作为默认编码。但是,我的生产数据库要求我使用UTF8(它托管在Heroku上,因此我别无选择)。
我创建了本地开发数据库以正确设置此设置:
sudo createdb -Upostgres $PROJECT_NAME --template=template0 \
--encoding=UTF8 --lc-collate=en_US.UTF-8 --lc-ctype=en_US.UTF-8
Run Code Online (Sandbox Code Playgroud)
但是,我现在无法运行django测试,因为测试数据库仅使用默认的Postgres集群设置(LATIN1),这会导致测试失败(某些模板中有无效字符- ...character 0xe28099 of encoding "UTF8" has no equivalent in "LATIN1")
'nuclear'选项是使用正确的(en_US.UTF8)设置重新安装Postgres,但是由于我是在VM中运行的,因此每次启动VM时,我都并不需要这样做。如果首先有一种方法可以按摩Django正确创建数据库,那将是更好的选择。
[更新1:TEST_ENCODING]
遵循@sneawo的建议,我设置了数据库的TEST_ENCODING属性,现在出现以下错误:
Creating test database for alias 'default'...
Got an error creating the test database: encoding UTF8 does not match locale en_US
DETAIL: The chosen LC_CTYPE setting requires encoding LATIN1.
Run Code Online (Sandbox Code Playgroud)
[更新2:核选项]
我在上面提到了这一点,但它并不适合所有人,但是由于我是在VM上运行它,因此对于我来说很容易在Vagrant设置脚本(shell脚本)中使用正确的排序规则重新创建postgres集群:
sudo service postgresql stop
sudo pg_dropcluster 9.1 --stop main
sudo pg_createcluster --start -e UTF-8 9.1 main
sudo cp -f $CONF_DIR/pg_hba.conf /etc/postgresql/9.1/main/pg_hba.conf
sudo cp -f $CONF_DIR/postgresql.conf /etc/postgresql/9.1/main/postgresql.conf
sudo service postgresql restart
Run Code Online (Sandbox Code Playgroud)
我有默认的“允许所有”版本,pg_hba.conf并且postgresql.conf从主机复制过来以覆盖创建群集时创建的默认设置。这是从大锤到破碎的解决方案,但它确实有效,而且很快。
在settings.py底部添加此代码
try:
from local_settings import *
except ImportError:
pass
Run Code Online (Sandbox Code Playgroud)
在 local_settings.py 中添加此代码
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_db',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '3306',
'OPTIONS': {
'charset': 'latin1',
'use_unicode': True, },
},
}
Run Code Online (Sandbox Code Playgroud)
将 local_settings.py 添加到 gitignore 中。