1. 程式人生 > 其它 >十分鐘cmdb 之 2021-01-19 Django2.2報錯 AttributeError: ‘str‘ object has no attribute ‘decode‘

十分鐘cmdb 之 2021-01-19 Django2.2報錯 AttributeError: ‘str‘ object has no attribute ‘decode‘

技術標籤:django開發python語言pythondjango

Django2.2報錯 AttributeError: 'str' object has no attribute 'decode'

準備將 Django 連線到 MySQL,在命令列輸入命令python manage.py makemigrations後報錯:AttributeError: 'str' object has no attribute 'decode'
出現這個錯誤之後可以根據錯誤提示找到檔案位置,開啟 operations.py 檔案,找到以下程式碼:

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

根據錯誤資訊提示,說明 if 語句執行時出錯, query 是 str 型別,而decode()是用來將 bytes 轉換成 string 型別用的,(關於Python編碼點這裡),由於 query 不需要解碼,所以直接將 if 語句註釋掉就可以了

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