Easy way to run "explain" on query sets in django

guidoism picture guidoism · Jul 13, 2012 · Viewed 9.8k times · Source

It seems like it should be easy to run "explain" directly off of a queryset in Django, but I don't see anything obvious for how to do it, and "explain" is a difficult thing to search for in the docs.

Answer

guidoism picture guidoism · Jul 13, 2012

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.