It seems like it should be easy to run "explain" directly off of a queryset in Django, but I don't see anything obvious for how to do it, and "explain" is a difficult thing to search for in the docs.
            Asked
            
        
        
            Active
            
        
            Viewed 1.9k times
        
    3 Answers
38
            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.
- 
                    10Please consider opening a ticket for django project. I would love to see this builtin. – Dmitry Shevchenko Jul 14 '12 at 00:39
- 
                    1Looks useful, would be even more so with an example of how to actually use it. – szeitlin Mar 15 '16 at 21:58
- 
                    Thank you! This is delicious! – mkoistinen Sep 09 '17 at 16:17
- 
                    There is a ticket to add a similar feature to django now : https://code.djangoproject.com/ticket/28574 – Tom Leys Mar 13 '18 at 22:27
- 
                    1How to use it ? – Bhawan Oct 18 '18 at 06:51
- 
                    1Do you include this at the bottom of the file or... where? – Will Taylor Feb 19 '19 at 17:51
- 
                    9This has been built into Django now https://github.com/django/django/blob/858cfd74e958b63e81657e5a9fc5f751c19e8192/django/db/models/query.py#L772-L773 – danihodovic Jul 14 '19 at 07:13
38
            
            
        QuerySet.explain(), available in Django 2.1.0 and above, is now the official way to explain queries.
 
    
    
        orn688
        
- 830
- 1
- 7
- 10
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()
 
    
    
        Pablo Ziliani
        
- 191
- 1
- 4
 
     
    