Print sql queries in jupyter notebook with django-extensions plugin

蹲街弑〆低调 提交于 2019-11-30 09:34:20

问题


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

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


回答1:


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.

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]

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'
)


来源:https://stackoverflow.com/questions/51362648/print-sql-queries-in-jupyter-notebook-with-django-extensions-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!