jupyter / notebook

Jupyter Interactive Notebook
https://jupyter-notebook.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
11.68k stars 4.92k forks source link

Printing well formatted sql queries in jupyter notebook with django-extensions plugin #4798

Open sant527 opened 5 years ago

sant527 commented 5 years ago

In Django i want to see the sql in jupyter notebook in the way same way shown using ipython

Eg:

python manage.py shell_plus --ipython --print-sql

In[1]: User.objects.all()
Out[1]: SELECT "user"."id",
       "user"."password",
       "user"."last_login",
       "user"."is_superuser",
       "user"."is_staff",
       "user"."date_joined",
       "user"."first_name",
       "user"."last_name",
       "user"."email",
       "user"."is_active",
       "user"."modified_date"
  FROM "user"
 LIMIT 21

Execution time: 0.001471s [Database: default]

<QuerySet [<User: yss@tst.com>]>

The sql is show in a very well formated way which is very easy to understand.

Now i want to try that in jupyter notebook

python manage.py shell_plus --notebook --print-sql

From here i followed the answer: https://stackoverflow.com/a/54632855

It says to install django_print_sql which i did then try to run

from django_print_sql import print_sql
with print_sql(count_only=False):
    q = User.objects.all()
[0 queries executed, total time elapsed 0.00ms]

django_print_sql: it says 0 queries and shows no sql output

Also i installed sqlparser and tried the solution mentioned

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

Out[1]: SELECT "user"."id",\n       "user"."password",\n       "user"."last_login",\n       "user"."is_superuser",\n       "user"."is_staff",\n       "user"."date_joined",\n       "user"."first_name",\n       "user"."last_name",\n       "user"."email",\n       "user"."is_active",\n       "user"."modified_date"
  FROM "user"
 LIMIT 21

The above sql does not look well formated at all.

So django_print_sql and sqlparser are not giving a colorful formatted sql which is given by the python manage.py shell_plus --ipython --print-sql

So how to get the sql in jupyter notebook for Django projects.

gaurav-arun commented 3 years ago

@sant527 Wrapping the sqlparse.format(...) in print() does the job. This is because sqlparse.format returns a raw formatted string.

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