Django Print out statements executed in the database

  • 2021-07-26 08:18:22
  • OfStack

First, let's introduce the statements executed in the database printed by Django

Sometimes we need to look at the SQL statement corresponding to models operation.

You can view it in the following way-

Add the following code at the end of the settings file in django project


LOGGING = {
  'version': 1,
  'disable_existing_loggers': False,
  'handlers': {
    'console': {
      'class': 'logging.StreamHandler',
    },
  },
  'loggers': {
    'django.db.backends': {
      'handlers': ['console'],
      'level': 'DEBUG' if DEBUG else 'INFO',
    },
  },
}

ps: Django View executed sql statement method

1. This method can only view select statements, but cannot view other updated and saved statements, and an error will be reported:


res = Province.objects.all()
print (res.query)
SELECT 'core_province'.'id', 'core_province'.'name', 'core_province'.'code' FROM 'core_province'

2. This method prints out all executed sql statements

1. Import connection first


from django.db import connection

2. Print in python file


print(connection.queries)
#  Print the last in the list 1 Article sql
# print(connection.queries[-1])

Summarize


Related articles: