I am trying to add an explain() method to django QuerySet, but get the MRO error:
File ".../mixin.py", line 10, in <module>
QuerySet.__bases__ += (QuerySetExplainMixin,)
TypeError: Cannot create a consistent method resolution
order (MRO) for bases QuerySetExplainMixin, object
the mixin and code I add it with:
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,)
(credits of the mixin: https://stackoverflow.com/a/39168237/3385534 )
This code was written for Python 2, that's why you get a conflict in Python 3, i cannot see another way than below to set the new method on the QuerySet
object :
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)
I hope this can help you.