1. 報(bào)錯(cuò)
相信很多人在使用python manage.py makemigrations
代碼進(jìn)行數(shù)據(jù)庫(kù)遷移的時(shí)候茵汰,往往會(huì)遇到以下錯(cuò)誤:"No module named 'MySQLdb"涉枫。
報(bào)錯(cuò)信息
2. 問(wèn)題分析
MySQLdb只支持Python2.,還不支持3.*版本
因此Python3中通過(guò)pip install mysqlclient
去安裝會(huì)一直報(bào)錯(cuò)
3. 解決辦法
Python3.* 中使用 PyMySQL 替代
3.1 安裝PyMySQL
pip install PyMySQL
3.2 數(shù)據(jù)庫(kù)配置無(wú)需改動(dòng)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 數(shù)據(jù)庫(kù)引擎
'NAME': 'djangoDB', # 數(shù)據(jù)庫(kù)名稱
'USER': 'root', # 用戶名
'PASSWORD': '123456', # 密碼
'HOST': '127.0.0.1', # 主機(jī)IP地址
'PORT': '3306' # 默認(rèn)端口
}
}
3.3 在項(xiàng)目根目錄下中的__init__.py
文件中添加以下代碼犀忱,保存:
import pymysql
pymysql.install_as_MySQLdb()
就可以用import MySQLdb
了募谎,其他的方法與MySQLdb一樣。
4. 但繼續(xù)運(yùn)行后可能還會(huì)報(bào)以下錯(cuò)誤:
django pymysql django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.None
這是由于使用PyMySQL替代mysqlclient后阴汇,版本認(rèn)證導(dǎo)致数冬。
解決辦法:
找到python安裝目錄下的base.py文件,目錄參考:/home/用戶名/.virtualenvs/項(xiàng)目名/lib/python3.5/site-packages/django/db/backends/mysql/base.py
修改以下兩行即可:
if version < (1, 3, 3):
# 注釋掉這一行搀庶,并加一句pass即可
# raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
pass