marco
marco

Reputation: 87

Run manage.py shell_plus --print-sql in Pycharm Django Console

Is there a way to configure Pycharm Django Console to run shell_plus from django_extensions? In particular, I want to print the SQL for every ORM operation. I've tried this script, passing the print_sql options, but its not working. Thank you in advance.

import sys
import django
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
if 'setup' in dir(django): django.setup()
import django_manage_shell; django_manage_shell.run(PROJECT_ROOT)
from django_extensions.management import shells
from django.core.management.color import color_style
style = color_style(force_color=True)
# Default settings for shell_plus
shell_plus_default_settings = {
    'ipython':         True,
    'print_sql':       True,
}
g = globals()
objects_to_import = shells.import_objects(shell_plus_default_settings, style)
g.update(objects_to_import)
print(style.NOTICE("Python %s on %s" % (sys.version, sys.platform)))
print(style.NOTICE("Django %s" % django.get_version()))
print(style.SUCCESS("Shell Prepared. Enjoy!"))

Upvotes: 1

Views: 1347

Answers (2)

mgphys
mgphys

Reputation: 241

You can enable SQL printing functionality inside PyCharm Django Console by utilising the monkey patch performed in django_extensions.management.debug_cursor.monkey_patch_cursordebugwrapper - simply activate the context manager inside your starting script (or in your currently open console) like so

monkey_patch_cursordebugwrapper(print_sql=True).__enter__()

Here's my entire console startup script: https://gist.github.com/gruuya/e837b3037781c715185d409499fabd7d

Note however, that due to the fact that PyCharm debugger needs to display the variables inside the Varibles pane, Django queries are no longer lazy, but are instead evaluated as soon as they are assigned to a variable (you could circumvent this by e.g. creating lambdas which execute the desired query).

Upvotes: 1

Duna C.
Duna C.

Reputation: 329

here's one that is working for me. One thing that's essential is the order things happen -- do the shell_plus stuff before django_manage_shell.run(...)

import sys; print('Python %s on %s' % (sys.version, sys.platform))
import django; print('Django %s' % django.get_version())
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
if 'setup' in dir(django): django.setup()
from django_extensions.management.shells import import_objects
from django.core.management.color import no_style

globals().update(import_objects({"dont_load": [], "quiet_load": False}, no_style()))
import django_manage_shell; django_manage_shell.run(PROJECT_ROOT)

Upvotes: 1

Related Questions