Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print sql query from Django as Debug is False

Tags:

django

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


like image 982
jia Jimmy Avatar asked May 25 '21 08:05

jia Jimmy


People also ask

How to get all SQL queries sent by Django from Py shell?

# To get all sql queries sent by Django from py shell import logging l = logging.getLogger ('django.db.backends') l.setLevel (logging.DEBUG) l.addHandler (logging.StreamHandler ()) Maybe you should take a look at django-debug-toolbar application, it will log all queries for you, display profiling information for them and much more.

How do I log SQL queries in Django?

Django comes with a built in way of logging all the SQL queries that it makes which can be incredibly useful. It’s pretty simple, just add this to your settings.py file: When you run queries in the console, and from the web server, you’ll be able to see them in the console:

How can I see the underlying query in Django?

If you don’t want to log all queries, but you have access to a QuerySet object you can call .query and print the result to see the underlying query: If you want even more information, there’s a great app you can add to your project called the Django Debug Toolbar which lets you see the queries happening while you navigate around your website.

What is an empty logger in Django?

The empty logger is a configuration for the root logger. In the example above, all loggers that aren't named "django.request" (or its children, e.g., "django.request.something") will propagate to the root logger. This allows you to put in log calls in your own project code and, in this case, have them show up in your console.


1 Answers

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")
like image 117
Abdul Aziz Barkat Avatar answered Oct 18 '22 00:10

Abdul Aziz Barkat