django2.2版本中pymysql报错'mysqlclient 1.3.13 or newer is required'解决办法
当你在使用 Djngo
进行数据迁移时,发生如下报错:
出现改报错的场景:
使用 Django
进行数据迁移 (pipenv run python manage.py makemigrations)
报错,但是本机已经安装 pymysq
错误定位:
- 虽然本地已安装了
PyMySQL
驱动,但Django
连接MySQL
时仍默认使用MySQLdb
驱动,但MySQLdb
并不支持Python3
,所以需要手动在项目中进行配置。
在项目根目录下的__init__.py
(setting同级目录)文件中添加如下代码:
import pymysql
pymysql.install_as_MySQLdb()
- 根据报错是在
base.py
第 36 行报的错,根据你的提示路径(Django-Blog-Xdgi4FFP/lib/python3.7/site-packages/django/db/backends/mysql/base.py)
打开base.py
,把 35、36 行注释掉:
34 version = Database.version_info
35 #if version < (1, 3, 13):
36 # raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required;
- 再次执行迁移命令,如果没有问题,可以忽略下面内容,如果执行迁移命令还是报错,且报错类型为:
File “/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/operations.py”, line 146, in last_executed_query
query = query.decode(errors=‘replace’)
AttributeError: ‘str’ object has no attribute ‘decode’
提示属性错误:“str”对象没有属性“decode”。
问题的在于 Python3
:
str 通过 encode() 转换成 bytes
bytes 通过 decode() 转换成 str
str 只有 encode() 方法,bytes 只有 decode() 方法!
解决方法:
根据提示打开报错的文件 operations.py
找到 146 行,把 decode
改成 encode
即可
def last_executed_query(self, cursor, sql, params):
141 # With MySQLdb, cursor objects have an (undocumented) “_executed”
142 # attribute where the exact query sent to the database is saved.
143 # See MySQLdb/cursors.py in the source distribution.
144 query = getattr(cursor, ‘_executed’, None)
145 if query is not None:
# 这里把 decode 改为 encode
146 query = query.encode(errors=‘replace’)
147 return query
再次执行迁移命令,即能进行数据迁移