设置Django / MySQL站点使用UTF-8

问题描述:

我想设置我的Django站点以一种万无一失的方式使用UTF-8 for MySQL,无论MySQL安装是否使用UTF-8作为默认值。除了使用UTF-8编码创建表之外,我还将以下内容添加到settings.py中的数据库初始化中,以确保连接也使用utf-8:

I want to set my Django site to use UTF-8 for MySQL in a foolproof way, regardless of whether the MySQL installation uses UTF-8 as its default. In addition to creating the tables with UTF-8 encoding, I added the following to my database initialization in settings.py to ensure the connection is also using utf-8:

'OPTIONS': { 'init_command': 'SET storage_engine=INNODB; SET names "utf8"' }

这会导致错误:

_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

正确的方法是什么?还有另一个需要执行SET NAMES的地方吗?

What is the right way to do this? Is there another place where the SET NAMES needs to be executed?

您只需要使用SET一次,并附加其他命令:

You need only using SET once only and appending others commands as:

'SET storage_engine=INNODB,character_set_connection=utf8,collation_connection=utf8_unicode_ci'

here