django 2.2和mysql使用的常見問題
可能是由于Django使用的MySQLdb庫對Python3不支持,我們用采用了PyMySQL庫來代替,導致出現(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默認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ù)名,應該是強制去把SQL轉(zhuǎn)換成str了
我靠?。?!這尼瑪官網(wǎng)2.2.1/2.2.2(當前最新版)的包不是害人么,記得該文件上面引入下這個方法
from django.utils.encoding import force_str
然后再執(zhí)行managa.py命令,可以了
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python連接mysql數(shù)據(jù)庫及簡單增刪改查操作示例代碼
這篇文章主要介紹了Python連接mysql數(shù)據(jù)庫及簡單增刪改查操作示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08Python?VisPy庫高性能科學可視化圖形處理用法實例探究
VisPy是一個用于高性能科學可視化的Python庫,它建立在現(xiàn)代圖形處理單元(GPU)上,旨在提供流暢、交互式的數(shù)據(jù)可視化體驗,本文將深入探討VisPy的基本概念、核心特性以及實際應用場景,并通過豐富的示例代碼演示其強大的可視化能力2023-12-12Python報錯NameError: name ‘secrets‘ is not
在使用Python進行安全編程時,我們經(jīng)常需要使用secrets模塊來生成安全的隨機數(shù),但是卻遇到這個問題,本文主要介紹了Python報錯NameError: name ‘secrets‘ is not defined解決,感興趣的可以了解一下2024-06-06在Python中定義函數(shù)并調(diào)用的操作步驟
這篇文章主要介紹了在Python中如何定義函數(shù)并調(diào)用它,函數(shù)的定義和調(diào)用是Python編程中最基本也是最重要的概念之一,掌握它們對于進行有效的Python編程至關(guān)重要,需要的朋友可以參考下2024-01-01