如何查看Django ORM的查询集对应的SQL查询?

发布于 2024-07-24 02:08:55 字数 126 浏览 9 评论 0原文

有没有办法可以打印 Django ORM 生成的查询?

假设我执行以下语句: Model.objects.filter(name='test')

如何查看生成的 SQL 查询?

Is there a way I can print the query the Django ORM is generating?

Say I execute the following statement: Model.objects.filter(name='test')

How do I get to see the generated SQL query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

人生百味 2024-07-31 02:08:55

每个 QuerySet 对象都有一个 query 属性,您可以将其记录或打印到 stdout 以进行调试。

qs = Model.objects.filter(name='test')
print(qs.query)

请注意,在 pdb 中,使用 p qs.query 将无法按预期工作,但 print(qs.query) 可以。

如果这不起作用,对于旧的 Django 版本,请尝试:

print str(qs.query)

编辑

我还使用了自定义模板标签(如 此代码段)将查询作为 HTML 注释注入单个请求的范围内。

Each QuerySet object has a query attribute that you can log or print to stdout for debugging purposes.

qs = Model.objects.filter(name='test')
print(qs.query)

Note that in pdb, using p qs.query will not work as desired, but print(qs.query) will.

If that doesn't work, for old Django versions, try:

print str(qs.query)

Edit

I've also used custom template tags (as outlined in this snippet) to inject the queries in the scope of a single request as HTML comments.

旧夏天 2024-07-31 02:08:55

您还可以使用 python 日志记录来记录 Django 生成的所有查询。 只需将其添加到您的设置文件中即可。

LOGGING = {
    'disable_existing_loggers': False,
    'version': 1,
    'handlers': {
        'console': {
            # logging handler that outputs log messages to terminal
            'class': 'logging.StreamHandler',
            'level': 'DEBUG', # message level to be written to console
        },
    },
    'loggers': {
        '': {
            # this sets root level logger to log debug and higher level
            # logs to console. All other loggers inherit settings from
            # root level logger.
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False, # this tells logger to send logging message
                                # to its parent (will send if set to True)
        },
        'django.db': {
            # django also has database level logging
            'level': 'DEBUG'
        },
    },
}

应用程序生成 html 输出的另一种方法 - django 调试工具栏 可以是用过的。

You also can use python logging to log all queries generated by Django. Just add this to your settings file.

LOGGING = {
    'disable_existing_loggers': False,
    'version': 1,
    'handlers': {
        'console': {
            # logging handler that outputs log messages to terminal
            'class': 'logging.StreamHandler',
            'level': 'DEBUG', # message level to be written to console
        },
    },
    'loggers': {
        '': {
            # this sets root level logger to log debug and higher level
            # logs to console. All other loggers inherit settings from
            # root level logger.
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False, # this tells logger to send logging message
                                # to its parent (will send if set to True)
        },
        'django.db': {
            # django also has database level logging
            'level': 'DEBUG'
        },
    },
}

Another method in case application is generating html output - django debug toolbar can be used.

趁年轻赶紧闹 2024-07-31 02:08:55

您可以将此代码粘贴到 Django shell 上,它将显示所有 SQL 查询:

import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())

You can paste this code on your Django shell which will display all the SQL queries:

import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
阳光的暖冬 2024-07-31 02:08:55

只要 DEBUG 开启:

from django.db import connection
print(connection.queries)

对于单个查询,您可以执行以下操作:

print(Model.objects.filter(name='test').query)

As long as DEBUG is on:

from django.db import connection
print(connection.queries)

For an individual query, you can do:

print(Model.objects.filter(name='test').query)
上课铃就是安魂曲 2024-07-31 02:08:55

也许您应该看一下 django-debug-toolbar 应用程序,它会为您记录所有查询,显示它们的分析信息等等。

Maybe you should take a look at django-debug-toolbar application, it will log all queries for you, display profiling information for them and much more.

阳光①夏 2024-07-31 02:08:55

一个强大的解决方案是将数据库服务器记录到一个文件,然后

tail -f /path/to/the/log/file.log

A robust solution would be to have your database server log to a file and then

tail -f /path/to/the/log/file.log
时光瘦了 2024-07-31 02:08:55

如果您使用数据库路由,则可能有多个数据库连接。
这样的代码可以让您查看会话中的连接。
您可以按照与单个连接相同的方式重置统计信息:reset_queries()

from django.db import connections,connection,reset_queries
...
reset_queries()  # resets data collection, call whenever it makes sense

...

def query_all():
    for c in connections.all():
        print(f"Queries per connection: Database: {c.settings_dict['NAME']} {c.queries}")

# and if you just want to count the number of queries
def query_count_all()->int:
    return sum(len(c.queries) for c in connections.all() )

If you are using database routing, you probably have more than one database connection.
Code like this lets you see connections in a session.
You can reset the stats the same way as with a single connection: reset_queries()

from django.db import connections,connection,reset_queries
...
reset_queries()  # resets data collection, call whenever it makes sense

...

def query_all():
    for c in connections.all():
        print(f"Queries per connection: Database: {c.settings_dict['NAME']} {c.queries}")

# and if you just want to count the number of queries
def query_count_all()->int:
    return sum(len(c.queries) for c in connections.all() )
寄居者 2024-07-31 02:08:55

Postgres Docker 容器

如果您在开发环境中使用 postgres docker 容器,则可以通过将此行添加到开发 docker-compose.yml postgres 容器配置中来轻松打开 SQL 日志记录:

command: ["postgres", "-c", "log_statement=all"]

然后查看数据库容器的日志。

优点

  • 通过取消注释/注释单行来打开/关闭日志记录
  • 适用于prefetch_lated
  • 适用于像Django Ninja这样的API框架(调试工具栏可能不需要)
  • 不需要对 Django 代码进行任何更改

缺点

  • Docker/Postgre 唯一的解决方案 - 启用日志记录的相同技术适用于任何数据库,但此答案的范围有限,
  • 显示的某些查询不感兴趣

Postgres Docker container

If you're using a postgres docker container in your development environment, you can easily switch on SQL logging by adding this line to your development docker-compose.yml postgres container configuration:

command: ["postgres", "-c", "log_statement=all"]

and then view the logs for the database container.

Pros

  • toggle on / off logging by uncommenting / commenting a single line
  • works with prefetch_related
  • works with API frameworks like Django Ninja (debug-toolbar may not)
  • doesn't require any changes to Django code

Cons

  • Docker/Postgre only solution -- the same technique of enabling logging would work for any database but this answer has limited scope
  • some queries shown are not of interest
来世叙缘 2024-07-31 02:08:55

您可以使用 Django debug_toolbar 来查看 SQL 查询。
debug_toolbar 使用分步指南:

安装 Debug_toolbar

pip install django-debug-toolbar

编辑 settings.py 文件 & 将 debug_toolbar 添加到已安装的应用程序,这应该添加到“django.contrib.staticfiles”下面。 还将 debug_toolbar 添加到中间件。

设置.py=>

INSTALLED_APPS= [ 'debug_toolbar'] 

MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']

在settings.py文件中创建一个名为INTERNAL_IPS的新列表

Settings.py=> 在 settings.py 文件末尾创建新列表; 添加以下列表:

INTERNAL_IPS= [127.0.0.1']

这将允许调试仅在内部开发服务器上运行

编辑#Project & 的 urls.py 文件 添加以下代码:

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
    url(r'^__debug__/', include(debug_toolbar.urls))       
    ] + urlpatterns

apply migrate & 再次运行服务器

您将在网页上看到一个附加组件,地址为 127.0.0.1 & 如果单击 SQL 查询复选框,您实际上还可以看到查询的运行时间。

You can use a Django debug_toolbar to view the SQL query.
Step by step guide for debug_toolbar usage :

Install the Debug_toolbar

pip install django-debug-toolbar

Edit settings.py file & add debug_toolbar to Installed apps, this should be added below to 'django.contrib.staticfiles'. Also add debug_toolbar to Middleware.

Settings.py=>

INSTALLED_APPS= [ 'debug_toolbar'] 

MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']

create a new list named INTERNAL_IPS in settings.py file

Settings.py=> create new list at the end of settings.py file & add below list:

INTERNAL_IPS= [127.0.0.1']

This will allow the debug to run only on internal developement server

Edit urls.py file of #Project & add below code:

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
    url(r'^__debug__/', include(debug_toolbar.urls))       
    ] + urlpatterns

apply migrate & run server again

You will see an add-on on your web page at 127.0.0.1 & if you click on SQL Query check box, you can actually see the run time of query as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文