Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
Last active April 3, 2024 22:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balazs-endresz/42c8f56dfaff12b33314859d71a189c6 to your computer and use it in GitHub Desktop.
Save balazs-endresz/42c8f56dfaff12b33314859d71a189c6 to your computer and use it in GitHub Desktop.
analyze explain django queryset
from django.db import connections
from django.db.models.query import QuerySet
def explain(self):
cursor = connections[self.db].cursor()
cursor.execute('set enable_seqscan = off')
query, params = self.query.sql_with_params()
print(query % params)
cursor.execute('EXPLAIN ANALYZE %s' % query, params)
explain = cursor.fetchall()
[print(x[0]) for x in explain]
cursor.execute('set enable_seqscan = on')
return self
QuerySet.explain = explain
# usage:
objects = SomeModel.objects.filter(...).explain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment