0

This question is different than log all sql queries

I tried logging configurations from the answers above they are not working as I would like them to work, so please read on.

What I want to do, is to make Django (1.11.x) debug server log SQL queries in such a way, that I can redirect them to *.sql file and immediately execute.

For this I need a SQL statements where all the variables are already substituted, so I DON'T want this:

WHERE some_column in (:arg1, :arg2, ...)

but I want this instead:

WHERE some_column in ('actual_value_1', 'actual_value2', ...)

Can you please help me figure out how to do this?

  1. Please note, that I don't want the SQL query to be printed in the browser (in some debug app like django_debug_toolbar) but printed to the console.

  2. Please note, that I don't want to type Django QuerySet queries in console - I want to type URL in browser, so make an actual HTTP request to Django debug server and see it printing a SQL query in such a way I can execute it later using SQL Plus or any other console tools.

mnowotka
  • 16,430
  • 18
  • 88
  • 134

2 Answers2

2

I think the tool I just made would be perfect for you.

https://pypi.python.org/pypi/django-print-sql

https://github.com/rabbit-aaron/django-print-sql

Install like this:

pip install --upgrade django-print-sql

Use like this in your view function:

from django_print_sql import print_sql

Class MyView(View):
    def get(self, request):
        with print_sql():
            User.objects.get(id=request.user.id)
            # and more....
rabbit.aaron
  • 2,369
  • 16
  • 25
0

This is a bit of a hack, because we have to strip the default django.db.backends log messages of the time taken and the args. After making these changes you should have a file of pure SQL that you are free to run as you wish...

First you want to set up your logging settings to reference our new log handler

Settings:

LOGGING = {
    'version': 1,
    'handlers': {
        'sql': {
            'level': 'DEBUG',
            'class': 'my_project.loggers.DjangoSQLFileHandler',
            'filename': '/path/to/sql.log'
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['sql'],
            'level': 'DEBUG'
        }
    }

}

Then you need to define your new handler and strip out the unwanted text from the message.

my_project.loggers.py:

from logging import FileHandler


class DjangoSQLFileHandler(FileHandler):

    def getMessage(self):
        msg = super(DjangoSQLFileHandler, self).getMessage()
        return record.msg.split(') ', 1)[1].split(';', 1)[0] + ';'
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50