Django 2.2 MySQL


Django2 使用 MySQL 稍复杂一些。

这是因为 Django 从 2.0 开始不再支持 Python2,只支持 Python3。但 MySQLdb 不支持 Python3。所以需要支持 Python3 的 PyMySQL 伪装 MySQLdb。伪装后还有些小问题,需要改源码。

准备

pip install pymysql

配置

settings.py

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'defpy',
        'PASSWORD': 'defpy.com',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

init.py

import pymysql
pymysql.install_as_MySQLdb()  # 兼容mysqldb

Bug

使用 PyMySQL 伪装 MySQLdb 的方案后会有2个bug,需要修改源码解决,修改安装包源码的方案不可取,但暂时没啥好办法先这样用吧。

mysqlclient 版本过低

异常信息:

  File "/Users/defpy/.local/share/virtualenvs/defpy.com-eAiAjDFX/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 36, in 
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决办法:打开这个文件注释掉 最低版本限制的判断

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

str 类型没有 decode 方法

异常信息:

    sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  File "/Users/defpy/.local/share/virtualenvs/defpy.com-eAiAjDFX/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'

解决办法:decode 改为 encode

# query = query.decode(errors='replace')
query = query.encode(errors='replace')