jia Jimmy
jia Jimmy

Reputation: 1848

How to print sql query from Django as Debug is False

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))


Upvotes: 7

Views: 462

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

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")

Upvotes: 5

Related Questions