django字符集与MySQL怪异

时间:2009-07-02 09:07:38

标签: mysql django django-models mysql-error-1267

我正在看

OperationalError (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")

看起来我的一些变量是UTF8字符串

'name':'p \ xc7 \ x9d \ xca \ x87 \ xc9 \ x9f \ xc4 \ xb1 \ xc9 \ xa5s徽章'

这是配置问题吗?如果是这样,我该如何解决?我想用Unicode处理所有内容(我认为)。

3 个答案:

答案 0 :(得分:42)

您可以通过shell更改表格编码:

$ manage.py shell
>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute('SHOW TABLES')
>>> results=[]
>>> for row in cursor.fetchall(): results.append(row)
>>> for row in results: cursor.execute('ALTER TABLE %s CONVERT TO CHARACTER SET utf8 COLLATE     utf8_general_ci;' % (row[0]))

https://mayan.readthedocs.org/en/v0.13/faq/index.html

答案 1 :(得分:11)

您的数据库似乎默认为latin1_swedish_ci,因此无法接受所有utf8字符。您需要更改MySQL数据库表的配置以使用utf8_general_ci。可以在MySQL Performance Blog

找到关于此的一篇好博文(包含指向工具的链接)

答案 2 :(得分:0)

您将在django设置文件中添加OPTIONS,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {'charset': 'utf8mb4'},
        'NAME': 'sarpanchDb',
        'USER': 'root',
        'PASSWORD': 'tiger',
        'HOST': 'localhost',
        'PORT': '',
    },
}

此外,您将需要在/etc/mysql/my.cnf文件中进行更改

[mysql]
default-character-set=utf8mb4

[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci

然后重新启动mysql服务

sudo service mysql restart

使用以下查询对它进行交叉检查是否有效

SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR 
Variable_name LIKE 'collation%';

您应该获得以下输出

+--------------------------+--------------------+
| Variable_name            | Value              |
+--------------------------+--------------------+
| character_set_client     | utf8mb4            |
| character_set_connection | utf8mb4            |
| character_set_database   | utf8mb4            |
| character_set_filesystem | binary             |
| character_set_results    | utf8mb4            |
| character_set_server     | utf8mb4            |
| character_set_system     | utf8               |
| collation_connection     | utf8mb4_unicode_ci |
| collation_database       | utf8mb4_unicode_ci |
| collation_server         | utf8mb4_unicode_ci |
+--------------------------+--------------------+
10 rows in set (0.00 sec)