django 2.2和mysql使用的常见问题

可能是由于Django使用的MySQLdb库对Python3不支持,我们用采用了PyMySQL库来代替,导致出现各种坑,特别是执行以下2条命令的是时候:

python manage.py makemigrations
or
python manage.py inspectdb

报错1:(提示你的mysqlclient版本过低),无论你是否执行pip install mysqlclient安装的最新版的,都抛出:

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None

使用注释大法解决:找到自己Python安装路劲下的Python36-32\Lib\site-packages\django\db\backends\mysql\base.py文件 将文件中的如下代码注释(可能需先关闭pycharm IDE)

if version < (1, 3, 3):
  raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)

报错2:(str类型没有decode方法)

py3默认str是unicode编码,通过encode方法编码成bytes类型,后者才有decode解码方法。提示错误来源:Python36\lib\site-packages\django\db\backends\mysql\operations.py", line 149, in last_executed_query

解决办法: 
    1. 再报错的Python36\lib\site-packages\django\db\backends\mysql\operations.py文件最上面添加 
    from django.utils.encoding import force_str
    2. 将last_executed_query方法中如下代码注释
    query = getattr(cursor, '_executed', None)
    if query is not None:
      query = query.decode(errors='replace')
    return query
    3. 在注释的代码下添加如下代码:
    return force_str(getattr(cursor, '_executed', None), errors='replace')
然后再次执行python manage.py makemigrations 成功

参考连接: https://www.zhangshengrong.com/p/281om6qgNw/

posted @ 2019-08-28 10:03  日出东海,我心向西  阅读(512)  评论(0编辑  收藏  举报