How to print a log of SQL statements when debugging Django
Xiaobian to share with you how to debug Django when printing SQL statements log, I hope you have something to gain after reading this article, let's discuss it together!
Add the following code to the settings:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, }}
Write your own method.
from django.db import connectionfrom django.db.models.query import QuerySetdef getSql(res): if type(res) == QuerySet: sql = str(res.query) else: queries = connection.queries sql = str(queries[-1].get ('sql '), ' utf-8') print ('\033 [1;34m' + '='* len(sql)) print(sql) print ('=' * len(sql)+'\033 [0 m') After reading this article, I believe you have a certain understanding of "How to print SQL statements logs when debugging Django". If you want to know more about it, please pay attention to the industry information channel. Thank you for reading!