使用python manage.py shell进入 shell,查询语句People.objects.get(id=11),经过什么样设置可以在shell中同时输出执行了哪些sql语句?
我的 Django 版本 1.8.10
老版本的 Django 可以使用以下的方法打印执行的 sql 语句,新版本貌似无效了。
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
2 answers
说个比较简单的方式吧,比如下面的代码:
>>> from django.contrib.auth.admin import User >>> User.objects.all() >>> u=User.objects.all() >>> print u.query SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
在这里直接将查询结果调用其query属性就可以获取其执行的结果了,只是你提供的那种方式是不想手动进行这么繁琐的操作而已
官方文档的回答 How can I see the raw SQL queries Django is running?
>>> from django.db import connection >>> connection.queries
通过这个方式,可以看所有的数据库查询,并不是很直观。
还有一种方式,
>>> a = Blog.objects.filter(entry__authors__name__isnull=True) >>> print a.query >>> Blog.objects.filter(entry__authors__name__isnull=True).query.sql_with_params()
Hot tools Tags
Hot Questions
Popular tool
vc9-vc14 (32+64 bit) runtime library collection (link below)
Download the collection of runtime libraries required for phpStudy installation
VC9 32-bit
VC9 32-bit phpstudy integrated installation environment runtime library
PHP programmer toolbox full version
Programmer Toolbox v1.0 PHP Integrated Environment
VC11 32-bit
VC11 32-bit phpstudy integrated installation environment runtime library
SublimeText3 Chinese version
Chinese version, very easy to use
Hot Topics
20529
7
13639
4






