欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django2.2报错::AttributeError: ''str'' object has no attribute ''decode''

程序员文章站 2024-03-25 11:33:10
...

遇到的错误:

AttributeError: ‘‘str’’ object has no attribute '‘decode’'

这基本是使用Django2.2的童鞋们经常遇到的问题!!!
下面给出 三种解决方法。
首先需要说明的是:
这三种解决方法时临时解决方法。
其次:
若以后童鞋们遇到更好的解决方法,可以在下方评论。
Django2.2报错::AttributeError: ''str'' object has no attribute ''decode''

方法一:

这个最简单粗暴!
直接将出错的两句代码给注释掉。

出错代码位于
/home/soul/anaconda3/lib/python3.6/site-packages/django/db/backends/mysql/operations.py
第140行

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

方法二:

这个方案看起来有些多余,对比 django 1.11版本代码以及代码段注释,这段代码加入的具体意义有些莫名其妙

但是为了保险起见,可以加入 try 方法达到另一种注释的方法

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)
    try:
        if query is not None:
            query = query.decode(errors='replace')
        return query
    except:
        return query

方法三:(推荐使用)

开源社区中,在最新的代码中, last_executed_query 函数被修改成如下:

# 19年11月27日,位于157行
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')

force_text 方法定义在 django/django/utils/encoding.py 的50行,对比代码发现force_text和force_str代码相同
Django2.2报错::AttributeError: ''str'' object has no attribute ''decode''
Django2.2报错::AttributeError: ''str'' object has no attribute ''decode''

这样就简单多了!!!
尝试修改代码

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
        return force_text(query, errors='replace')

运行测试:

(base) [aaa@qq.com one_orm]$ python manage.py makemigrations
No changes detected

欧克了!!!
至此:问题解决!举手啦,鼓掌鼓掌。
Django2.2报错::AttributeError: ''str'' object has no attribute ''decode''

相关标签: python bug django