尝试将first_name,last_name保存到Django的auth_user模型时,出现奇怪的错误消息。
失败的例子
user = User.object.create_user(username, email, password) user.first_name = u'Rytis' user.last_name = u'Slatkevičius' user.save() >>> Incorrect string value: '\xC4\x8Dius' for column 'last_name' at row 104 user.first_name = u'Валерий' user.last_name = u'Богданов' user.save() >>> Incorrect string value: '\xD0\x92\xD0\xB0\xD0\xBB...' for column 'first_name' at row 104 user.first_name = u'Krzysztof' user.last_name = u'Szukiełojć' user.save() >>> Incorrect string value: '\xC5\x82oj\xC4\x87' for column 'last_name' at row 104
成功的例子
user.first_name = u'Marcin' user.last_name = u'Król' user.save() >>> SUCCEED
MySQL设置
mysql> show variables like 'char%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.00 sec)
表字符集和排序规则
表auth_user具有utf-8字符集,并带有utf8_general_ci排序规则。
UPDATE命令的结果
使用UPDATE命令将上述值更新到auth_user表时,它没有引发任何错误。
mysql> update auth_user set last_name='Slatkevičiusa' where id=1; Query OK, 1 row affected, 1 warning (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select last_name from auth_user where id=100; +---------------+ | last_name | +---------------+ | Slatkevi?iusa | +---------------+ 1 row in set (0.00 sec)
PostgreSQL的
当我在Django中切换数据库后端时,上面列出的失败值可以更新到PostgreSQL表中。真奇怪。
mysql> SHOW CHARACTER SET; +----------+-----------------------------+---------------------+--------+ | Charset | Description | Default collation | Maxlen | +----------+-----------------------------+---------------------+--------+ ... | utf8 | UTF-8 Unicode | utf8_general_ci | 3 | ...
但是从http://www.postgresql.org/docs/8.1/interactive/multibyte.html,我发现了以下内容:
Name Bytes/Char UTF8 1-4
这是否意味着unicode char在PostgreSQL中的maxlen为4个字节,而在MySQL中为3个字节,这导致了上述错误?
我遇到了同样的问题,并通过更改列的字符集解决了它。即使你的数据库具有默认字符集,utf-8我认为数据库列在MySQL中也可能具有不同的字符集。这是我使用的SQL查询:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;