Django显示SQL语句
Django显示SQL语句
1、使用connection
显示
导入:from django.db import connection
获取SQL语句:connection.queries
样例
@action(detail=False)
def test_print_sql(self, request):
from django.db import connection
groups = Group.objects.all()
print(f"所有的组:{groups}")
master = Group.objects.filter(name="master组").first()
print(f"master组:{master}")
admin = Group.objects.filter(name="admin组").first()
print(f"admin组:{admin}")
in_sql = Group.objects.filter(name__in=["master组", "dev组", "不存在的组"]).first()
print(f"in语句的sql:{in_sql}")
Group(gid="test组", name="测试组").save()
print("插入单条数据")
Group.objects.bulk_create([Group(gid="组1", name="组1"), Group(gid="组2", name="组2"), Group(gid="组3", name="组3"),
Group(gid="组4", name="组4")])
print("批量创建")
for o in connection.queries:
print(f"SQL语句:{o}")
return Response(status=status.HTTP_200_OK, data="测试显示SQL语句")
运行
![image-20220712163722779](https://img2022.cnblogs.com/blog/1768648/202207/1768648-20220712164906401-1636529218.png)
2、配置log显示
在Django项目的settings.py文件中,在最后复制粘贴如下代码:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}