Last active
April 3, 2024 22:58
-
-
Save balazs-endresz/42c8f56dfaff12b33314859d71a189c6 to your computer and use it in GitHub Desktop.
analyze explain django queryset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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