django.db.utils.OperationalError: 1366

本文详细介绍了如何在Django中配置和使用utf8mb4字符集,以解决Unicode字符编码问题。通过修改settings.py文件和Django的MySQL后端代码,确保数据库连接正确设置字符集,并提供了一种在App Engine Django教程中遇到的特定问题解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The standard way to get utf8mb4 working in Django is to specify it as DATABASES['default']['OPTIONS'] in settings.py, like this:

    'OPTIONS': {'charset': 'utf8mb4'},

The workaround is to manually call SET NAMES; edit lib/django/db/backends/mysql/base.py and add a conn.query("SET NAMES utf8mb4") line into DatabaseWrapper.get_new_connection, so it looks like this:

    def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        conn.query("SET NAMES utf8mb4")
        return conn

Make sure that you also have utf8mb4 enabled on the backend.  The migration commands in the App Engine Django tutorial result in a Cloud SQL instance configured for utf8.  I needed to run these commands to enable utf8mb4 on the two tables:

    ALTER TABLE ap_ruckus_brushstatus CONVERT TO CHARACTER SET utf8mb4;
    ALTER TABLE ap_ruckus_brushstatus CONVERT TO CHARACTER SET utf8mb4;
Let me know if that fixes your problem. There is a real fix in the pipeline but no timetable for it to be out.

     'OPTIONS': {
         'autocommit': True,
         'charset': 'utf8mb4',
     },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值