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

前端 未结 3 578
闹比i
闹比i 2020-12-24 12:10

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 t

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 12: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.

提交回复
热议问题