1. 程式人生 > >Django shell除錯models輸出的SQL語句

Django shell除錯models輸出的SQL語句

在settings.py裡,配置如下logging:

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

使用效果:

$ python manage.py shell

In [1]: from test.models import A

In [2]: A.objects.all()
(0.001) SELECT "app1_a"."id", "app1_a"."name" FROM "app1_a" LIMIT 21; args=()
[<A: A object>]

在shell命令列的環境下,可以使用 django-exension’s shell_plus 命令並開啟 --print-sql 選項。

python manage.py shell_plus --print-sql

>>> Author.objects.all()
SELECT "library_author"."id", "library_author"."name" FROM "library_author" LIMIT 21
Execution time: 0.001393s [Database: default]
<QuerySet [<Author: Author object>]>