Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to run "explain" on query sets in django

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.

like image 528
guidoism Avatar asked Jul 13 '12 18:07

guidoism


People also ask

How do I run a query in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What is the use of QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

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.

like image 90
guidoism Avatar answered Sep 21 '22 21:09

guidoism