Skip to content

Instantly share code, notes, and snippets.

@adam-stokes
Forked from allixsenos/explain.py
Created September 12, 2017 16:32
Show Gist options
  • Save adam-stokes/089edc587fc825830b1b93685cc122ef to your computer and use it in GitHub Desktop.
Save adam-stokes/089edc587fc825830b1b93685cc122ef to your computer and use it in GitHub Desktop.
Django QuerySet Explain
from django.db import connections
from django.db.models.query import QuerySet
from __future__ import print_function
class QuerySetExplainMixin:
def explain(self, analyze=True):
cursor = connections[self.db].cursor()
print(self.query)
print()
sql, params = self.query.sql_with_params()
cursor.execute('EXPLAIN %s %s' % ("ANALYZE" if analyze else "", sql), params)
map(lambda x: print(x[0]), cursor.fetchall())
return None
QuerySet.__bases__ += (QuerySetExplainMixin,)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment