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

前端 未结 3 545
闹比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:25

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 12:42

    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()
    
    0 讨论(0)
提交回复
热议问题