39👍
✅
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.
38👍
QuerySet.explain()
, available in Django 2.1.0 and above, is now the official way to explain queries.
- [Django]-How to create a custom decorator in Django?
- [Django]-Django most efficient way to count same field values in a query
- [Django]-Import error 'force_text' from 'django.utils.encoding'
19👍
Just a slight modification to guidoism’s answer. This prevents getting a ProgrammingError: syntax error at or near ...
error caused by the parameters not being correctly escaped in the raw query:
from django.db import connections
from django.db.models.query import QuerySet
class QuerySetExplainMixin:
def explain(self):
cursor = connections[self.db].cursor()
query, params = self.query.sql_with_params()
cursor.execute('explain %s' % query, params)
return '\n'.join(r[0] for r in cursor.fetchall())
QuerySet.__bases__ += (QuerySetExplainMixin,)
To use, simply invoke explain() at the end of your queryset, e.g.:
print SomeModel.objects.filter(...).explain()
- [Django]-Django post_save preventing recursion without overriding model save()
- [Django]-Django template convert to string
- [Django]-Django admin make a field read-only when modifying obj but required when adding new obj
Source:stackexchange.com