About Debugging SQL Queries in GraphQL with Graphene-Django

You can inspect the Graphene-Django database queries and their execution time using the graphene_django.debug.DjangoDebugMiddleware. Note, that this is not a Django middleware, and it must be placed in the GRAPHENE settings in your settings file:

1
2
3
4
5
6
GRAPHENE = {
    "SCHEMA": "myproject.schema.schema",
    "MIDDLEWARE": [
        "graphene_django.debug.DjangoDebugMiddleware",
    ],
}

In your schema.py file, add a custom field "_debug" which will return meaningful info only if the middleware is activated:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import graphene
from graphene_django.debug import DjangoDebug

class Query(graphene.ObjectType):
    ...
    debug = graphene.Field(DjangoDebug, name='_debug')

    def resolve_debug(self, info, **kwargs):
        if hasattr(DjangoDebug, "resolve_debug"):
            return DjangoDebug.resolve_debug(info)

schema = graphene.Schema(query=Query)

Query the debug info as the last field, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{
  allPosts {
    id
    title
    content
  }
  allAds {
    id
    title
    url
  }
  _debug {
    sql {
      rawSql
      duration
    }
  }
}

Tips and Tricks Programming Databases Debugging Django 5.x Django 4.2 Django 3.2 Graphene-Django GraphQL