溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在django 2.2中使用mysql

發(fā)布時(shí)間:2021-03-24 16:28:54 來(lái)源:億速云 閱讀:140 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)怎么在django 2.2中使用mysql,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

第一個(gè)坑(提示你的mysqlclient版本過(guò)低)

無(wú)聊你是否執(zhí)行pip install mysqlclient安裝的最新版的,都拋出:

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None

MD,LZ看到這錯(cuò)誤太想罵人了,沒(méi)辦法采取網(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__)

第二個(gè)坑(str類型沒(méi)有decode方法)

對(duì)對(duì)對(duì),py3默認(rèn)str是unicode編碼,通過(guò)encode方法編碼成bytes類型,后者才有decode解碼方法。
提示錯(cuò)誤來(lái)源:Python36\lib\site-packages\django\db\backends\mysql\operations.py", line 149, in last_executed_query

這里網(wǎng)上一搜一堆的把encode改成decode方法,我靠,這誰(shuí)的腦洞無(wú)敵了
源方法內(nèi)容(pip安裝的django 2.2.1原封不動(dòng)的內(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

通過(guò)print大法輸出query結(jié)果,內(nèi)容為

SELECT @@SQL_AUTO_IS_NULL

數(shù)據(jù)類型為str

這里網(wǎng)上還有注釋大法,LZ不知道注釋了if的后遺癥是啥有沒(méi)有影響,于是也沒(méi)采納。

于是我去django的github去翻這個(gè)文件這個(gè)方法的最新/歷史版本,結(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)前最新版)的包不是害人么,記得該文件上面引入下這個(gè)方法

from django.utils.encoding import force_str

以上就是怎么在django 2.2中使用mysql,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI