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