Skip to content

Instantly share code, notes, and snippets.

@vladborovtsov
Forked from allixsenos/explain.py
Created April 29, 2016 09:18
Show Gist options
  • Save vladborovtsov/32711dcba10bf8c090d8e535f48c9a19 to your computer and use it in GitHub Desktop.
Save vladborovtsov/32711dcba10bf8c090d8e535f48c9a19 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