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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With