6

From doc how can I see the raw SQL queries Django is running?

I can get sql executed by:

from django.db import connection
connection.queries

But it's only available while Debug == True

How to print sql as Debug == False?

Thanks

Update

I want something like this:

from django.db import connection
from django.db import reset_queries

reset_queries()  # Clears the query.
with transaction.atomic():
    r = Amodel.objects.create(
        ...
    )

    Bmodel.objects.filter(id__in=handle_ids_).update(status=4)

# Prints the sql executed in this transaction block.
logger.info("[sql_execute]: {}".format(connection.queries))


Hagyn
  • 922
  • 7
  • 14
jia Jimmy
  • 1,693
  • 2
  • 18
  • 38
  • do you want to see all queries or only some particular? – Sergey Pugach May 25 '21 at 08:06
  • Does this answer your question? [How can I see the raw SQL queries Django is running?](https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running) – NKSM May 25 '21 at 08:35

1 Answers1

4

You can work with Database instrumentation [Django docs] which basically provides a hook for installing wrapper functions around the execution of database queries. Using this you can simply make a wrapper like so:

class QueryLogger:

    def __init__(self):
        self.queries = []
        self.errored = False

    def __call__(self, execute, sql, params, many, context):
        current_query = {'sql': sql, 'params': params, 'many': many}
        try:
            result = execute(sql, params, many, context)
        except Exception as e:
            self.errored = True
            current_query['status'] = 'error'
            current_query['exception'] = e
            raise
        else:
            current_query['status'] = 'ok'
            return result
        finally:
            self.queries.append(current_query)

Then use it in your view:

from django.db import connection


ql = QueryLogger()

with connection.execute_wrapper(ql), transaction.atomic():
    r = Amodel.objects.create(
        ...
    )
    Bmodel.objects.filter(id__in=handle_ids_).update(status=4)

if not ql.errored:
    for query in ql.queries:
        print(query)
else:
    print("Some error occured")
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33