3

我正在尝试向 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 )

4

1 回答 1

3

这段代码是为 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)

我希望这可以帮助你。

于 2017-08-21T21:07:02.413 回答