python manage.py test报错

django.db.utils.OperationalError: 1366

测试数据有中文时,测试生成的数据库编码不对报错,如下:

python manage.py test
    Creating test database for alias 'default'...
    Got an error creating the test database: (1007, "Can't create database 'test_xservice'; database exists")
    Type 'yes' if you would like to try deleting the test database 'test_xservice', or 'no' to cancel: yes
    Destroying old test database for alias 'default'...
    Traceback (most recent call last):
      File "/home/swot/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
        return self.cursor.execute(sql, params)
      File "/home/swot/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute
        return self.cursor.execute(query, args)
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute
        self.errorhandler(self, exc, value)
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
        raise errorvalue
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute
        res = self._query(query)
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query
        rowcount = self._do_query(q)
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query
        db.query(q)
      File "/home/swot/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query
        _mysql.connection.query(self, query)
    _mysql_exceptions.OperationalError: (1366, "Incorrect string value: '\\xE8\\xAE\\xBE\\xE5\\xA4\\x87' for column 'name' at row 7")

处理方法:

settings.py DATABASES 设置 TEST 的 CHARSET 和 COLLATION 编码即可。

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': 'YOUR_DATABASE_NAME',                      # Or path to database file if using sqlite3.
            # 'NAME': os.path.basename(BASE_DIR),
            # The following settings are not used with sqlite3:
            'USER': 'YOUR_USER',
            'PASSWORD': 'YOUR_PASSWORD',
            'HOST': '127.0.0.1',         # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
            'PORT': '',         # Set to empty string for default.
            'TEST': {
                'CHARSET': 'utf8',
                'COLLATION': 'utf8_general_ci',
            }
        }
    }

参考: https://docs.djangoproject.com/en/2.0/ref/settings/#charset

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值