Easy way to run “explain” on query sets in django

Well, there seems to be nothing out there except a toolbar so I wrote my own mixin to give me an explain() method on my querysets:

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

class QuerySetExplainMixin:
    def explain(self):
        cursor = connections[self.db].cursor()
        cursor.execute('explain %s' % str(self.query))
        return cursor.fetchall()

QuerySet.__bases__ += (QuerySetExplainMixin,)

Hopefully this is useful to others.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)