Print sql queries in jupyter notebook with django-

2019-07-14 19:10发布

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条回答
别忘想泡老子
2楼-- · 2019-07-14 20:02

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'
)
查看更多
登录 后发表回答