SoFunction
Updated on 2024-11-16

Sample code to print logs of SQL statements when debugging Django

This article introduces the debugging Django when printing SQL statements in the log code examples, the text of the sample code through the introduction of the very detailed, for everyone to learn or work with some reference to the learning value, you can refer to the next!

Add the following code inside the settings:

LOGGING = {
  'version': 1,
  'disable_existing_loggers': False,
  'handlers': {
    'console':{
      'level':'DEBUG',
      'class':'',
    },
  },
  'loggers': {
    '': {
      'handlers': ['console'],
      'propagate': True,
      'level':'DEBUG',
    },
  }
}

Write your own method.

from  import connection
from  import QuerySet
def getSql(res):
  if type(res) == QuerySet:
    sql = str()
  else:
    queries = 
    sql = str(queries[-1].get('sql'), 'utf-8')
  print('\033[1;34m' + '=' * len(sql))
  print(sql)
  print('=' * len(sql) + '\033[0m')

This is the whole content of this article.