在 django 框架执行数据迁移的时候,常会遇到报错:
query = query.decode(errors=‘replace’) AttributeError: ‘str’ object has no attribute ‘decode’
常见低版本的Django 比如 :Django2.2.5
python3.8 + Django2.2.5
query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
File "/home/python/.virtualenvs/luffyapi/lib/python3.8/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
按照报错提示的地方点进去修改:
修改前 :query = query.decode(errors=‘replace’)
修改后: query = query.encode(errors=‘replace’)
再重新执行 :
python manage.py makemigrations
python manage.py migrate
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.encode(errors='replace')
return query