djangosql-execution-plan

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


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.


Solution

  • 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.