django 2.2和mysql使用的常見問題
可能是由于Django使用的MySQLdb庫對Python3不支持,我們用采用了PyMySQL庫來代替,導(dǎo)致出現(xiàn)各種坑,特別是執(zhí)行以下2條命令的是時候:
python manage.py makemigrations or python manage.py inspectdb
第一個坑(提示你的mysqlclient版本過低)
無聊你是否執(zhí)行pip install mysqlclient安裝的最新版的,都拋出:
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
MD,LZ看到這錯誤太想罵人了,沒辦法采取網(wǎng)上的方法,注釋大法!
找到Python安裝路勁下的Python36-32\Lib\site-packages\django\db\backends\mysql\base.py文件
將文件中的如下代碼注釋(可能需先關(guān)閉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默認(rèn)str是unicode編碼,通過encode方法編碼成bytes類型,后者才有decode解碼方法。
提示錯誤來源:Python36\lib\site-packages\django\db\backends\mysql\operations.py", line 149, in last_executed_query
這里網(wǎng)上一搜一堆的把encode改成decode方法,我靠,這誰的腦洞無敵了
源方法內(nèi)容(pip安裝的django 2.2.1原封不動的內(nèi)容):
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結(jié)果,內(nèi)容為
SELECT @@SQL_AUTO_IS_NULL 數(shù)據(jù)類型為str
這里網(wǎng)上還有注釋大法,LZ不知道注釋了if的后遺癥是啥有沒有影響,于是也沒采納。
于是我去django的github去翻這個文件這個方法的最新/歷史版本,結(jié)果最新master分支內(nèi)容如下:
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')
看函數(shù)名,應(yīng)該是強(qiáng)制去把SQL轉(zhuǎn)換成str了
我靠?。?!這尼瑪官網(wǎng)2.2.1/2.2.2(當(dāng)前最新版)的包不是害人么,記得該文件上面引入下這個方法
from django.utils.encoding import force_str
然后再執(zhí)行managa.py命令,可以了
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python中pandas庫的iloc函數(shù)用法解析
在 Pandas 中,.iloc 是一種用于基于整數(shù)位置進(jìn)行索引的屬性,可以用于獲取 DataFrame 或 Series 中的數(shù)據(jù),這篇文章主要介紹了python中pandas庫的iloc函數(shù)用法,需要的朋友可以參考下2023-05-05
Python處理JSON數(shù)據(jù)并導(dǎo)入Neo4j數(shù)據(jù)庫
在數(shù)據(jù)處理和分析中,JSON是一種常見的數(shù)據(jù)格式,Neo4j是一個高性能的圖數(shù)據(jù)庫,能夠存儲和查詢復(fù)雜的網(wǎng)絡(luò)關(guān)系,下面我們就來看看Python如何處理JSON數(shù)據(jù)并導(dǎo)入Neo4j數(shù)據(jù)庫吧2024-11-11
使用keras實(shí)現(xiàn)非線性回歸(兩種加激活函數(shù)的方式)
這篇文章主要介紹了使用keras實(shí)現(xiàn)非線性回歸(兩種加激活函數(shù)的方式),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Pytorch 使用 nii數(shù)據(jù)做輸入數(shù)據(jù)的操作
這篇文章主要介紹了Pytorch 使用 nii數(shù)據(jù)做輸入數(shù)據(jù)的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
python 生成器協(xié)程運(yùn)算實(shí)例
下面小編就為大家?guī)硪黄猵ython 生成器協(xié)程運(yùn)算實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

