Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sant527 opened this issue Aug 1, 2019 · 1 comment

Comments

@sant527
Copy link

sant527 commented Aug 1, 2019

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants