Search code examples
sqldjangoormcomments

Is it possible to add SQL comments to a query built with the ORM?


I am trying to identify slow queries in a large-scale Django 1.3 web application. As it is kind of difficult to match the raw sql query in the slow query log with the specific ORM statement in the code, I wondered if it is possible to add a SQL comment to the query constructed with the ORM, something like..

Object.objects.filter(Q(pub_date__lte=datetime.now)).comment('query no. 123')

Solution

  • For those reading in 2022 onwards - there is a much better answer these days:

    Google's sqlcommenter project has a Django middleware

    [A] Django middleware whose purpose is to augment a SQL statement right before execution, with information about the controller and user code to help with later making database optimization decisions, after those statements are examined from the database server’s logs.