TypeError:无法为基础Mixin,object创建一致的MRO

时间:2017-08-21 18:10:45

标签: django python-3.x method-resolution-order

我正在尝试向django QuerySet添加一个explain()方法,但是得到了MRO错误:

File ".../mixin.py", line 10, in <module>

    QuerySet.__bases__ += (QuerySetExplainMixin,)
TypeError: Cannot create a consistent method resolution
order (MRO) for bases QuerySetExplainMixin, object

mixin和我添加的代码:

from django.db import connections
from django.db.models.query import QuerySet

class QuerySetExplainMixin:
    def explain(self):
        cursor = connections[self.db].cursor()
        query, params = self.query.sql_with_params()
        cursor.execute('explain %s' % query, params)
        return '\n'.join(r[0] for r in cursor.fetchall())

QuerySet.__bases__ += (QuerySetExplainMixin,)

(mixin的信用:https://stackoverflow.com/a/39168237/3385534

1 个答案:

答案 0 :(得分:2)

这段代码是为Python 2编写的,这就是为什么你在Python 3中遇到冲突的原因,我在下面找不到另一种方法来在QuerySet对象上设置新方法:

from django.db import connections
from django.db.models.query import QuerySet

def explain(self):
    cursor = connections[self.db].cursor()
    query, params = self.query.sql_with_params()
    cursor.execute('explain %s' % query, params)
    return '\n'.join(r[0] for r in cursor.fetchall())

type.__setattr__(QuerySet, 'explain', explain)

我希望这可以帮到你。