Easy way to run “explain” on query sets in django

吃可爱长大的小学妹 提交于 2019-12-18 11:03:06

问题


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.


回答1:


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.




回答2:


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()



回答3:


QuerySet.explain(), available in Django 2.1.0 and above, is now the official way to explain queries.



来源:https://stackoverflow.com/questions/11476664/easy-way-to-run-explain-on-query-sets-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!