可能是由於Django使用的MySQLdb庫對Python3不支持,我們用採用了PyMySQL庫來代替,導致出現各種坑,特別是執行以下2條命令的是時候:
python manage.py makemigrations
or
python manage.py inspectdb
第一個坑(提示你的mysqlclient版本過低)
無聊你是否執行pip install mysqlclient安裝的最新版的,都拋出:
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
MD,LZ看到這錯誤太想罵人了,沒辦法採取網上的方法,註釋大法!
找到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__)
第二個坑(str類型沒有decode方法)
對對對,py3默認str是unicode編碼,通過encode方法編碼成bytes類型,後者纔有decode解碼方法。
提示錯誤來源:Python36\lib\site-packages\django\db\backends\mysql\operations.py", line 149, in last_executed_query
- 這裏網上一搜一堆的把encode改成decode方法,我靠,這誰的腦洞無敵了
源方法內容(pip安裝的django 2.2.1原封不動的內容):
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
if query is not None:
query = query.decode(errors='replace')
return query
通過print大法輸出query結果,內容爲
SELECT @@SQL_AUTO_IS_NULL
數據類型爲str
- 這裏網上還有註釋大法,LZ不知道註釋了if的後遺症是啥有沒有影響,於是也沒采納。
於是我去django的github去翻這個文件這個方法的最新/歷史版本,結果最新master分支內容如下:
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
# MySQLdb returns string, PyMySQL bytes.
return force_str(getattr(cursor, '_executed', None), errors='replace')
看函數名,應該是強制去把SQL轉換成str了
我靠!!!這尼瑪官網2.2.1的包不是害人麼,記得該文件上面引入下這個方法
from django.utils.encoding import force_str
然後再執行managa.py命令,可以了