准備將 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