项目常用方法2,方法1可用于分析执行速度,执行时间。
1, django_extensions SQL解析
① pip install django-extensions
② INSTALLED_APPS = [
代码语言:txt复制'django_extensions',
]
③ python manage.py shell_plus --print-sql
代码语言:javascript复制INSTALLED_APPS = [
...
'django_extensions', # sql log出力
]
代码语言:javascript复制(venv) PS D:PycharmProjectspj> python manage.py shell_plus --print-sql
......
>>> User.objects.only('username','first_name','email')
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."email"
FROM "auth_user"
LIMIT 21
Execution time: 0.004991s [Database: default]
<QuerySet [<User: purchase007>, <User: purchase001>, <User: purchase005>, <User: purchase008>, <User: purchase004>, <User: purchase006>, <User: admin>, <User: purchase003>, <User: purchase002>]>
2, pjsettings.py:LOGGING > django.db.backends
「django.db.backends」设定,启动website后,执行的sql都会打印到终端
代码语言:python代码运行次数:0复制import os
ROOT_LOG_LEVEL = 'DEBUG' if DEBUG else 'INFO'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
"formatters": {
"simple": {
"format": "%(asctime)s [%(levelname)s] %(message)s"
},
"verbose":{
"format": "%(asctime)s [%(levelname)s] P%(process)d t%(thread)d %(pathname)s:%(lineno)d %(message)s"
}
},
'handlers': {
'console_simple': {
'class': 'logging.StreamHandler',
"formatter": "simple",
},
'console_verbose': {
'class': 'logging.StreamHandler',
"formatter": "verbose",
},
},
'root': {
'handlers': ['console_verbose'],
'level': ROOT_LOG_LEVEL,
},
'loggers': {
'django': {
'handlers': ['console_verbose'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
'propagate': False,
},
'django.db.backends': {
'handlers': ['console_verbose'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
'propagate': False,
},
},
上边配置了很多参数,以下为简化版。
代码语言:javascript复制LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
3,django-print-sql 没试,要写入代码,用于解析。写完还得删除。。麻烦
django-print-sql