使用Django扩展插件在Jupyter Notebook中打印SQL查询 [英] Print sql queries in jupyter notebook with django-extensions plugin

查看:234
本文介绍了使用Django扩展插件在Jupyter Notebook中打印SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像在以下命令中那样显示SQL查询:python manage.py shell_plus --print-sql但在Jupyter Notebook中?

Is it possible to show SQL queries like in this command: python manage.py shell_plus --print-sql but in Jupyter Notebook?

我尝试了此命令python manage.py shell_plus --notebook --print-sql,但是没有用.

I tried this command python manage.py shell_plus --notebook --print-sql but it not worked.

推荐答案

这可能是Django Extensions中的一个错误,您没有看到SQL查询.几个版本之前,有人在这里问如何在Jupyter中禁用SQL打印.

It's probably a bug in Django Extensions that you don't see SQL queries. A few versions ago, someone asked here how to disable SQL printing in Jupyter.

作为解决方法,您可以使用 django_print_sql :

As a workaround, you could use django_print_sql:

from django_print_sql import print_sql
with print_sql(count_only=False):
    User.objects.count()

您甚至可能会发现,控制要打印的查询胜于全部打印.

You may even find that having control over which queries to print is preferable to printing all.

但是我主要只是追溯地打印最后一个查询:

But I mostly just print the last query retroactively:

from django import db
db.connection.queries[-1]

如果您要使用 sqlparse 漂亮地打印查询,它会变得越来越复杂,以至于实用功能:

If you want to pretty-print the query with sqlparse, it starts getting complicated enough for a utility function:

import sqlparse
sqlparse.format(
    db.connection.queries[-1]['sql'], 
    reindent=True, 
    keyword_case='upper'
)

这篇关于使用Django扩展插件在Jupyter Notebook中打印SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆