Django-Extensions: how to add local variables to shell_plus

I have multiple dictionaries, and I want each key/value pair to be defined in the local scope of a django-extensions shell_plus session.

My current management command looks something like this:

import django
import code

devs = {
    'hot_water': object()
    'air': object()
}
procs = {
    'clean_keg': lambda x: 'do_something'
}

# unnecessary code when using `shell_plus`
model_map = { model.__name__: model for model in django.apps.apps.get_models() }

local = {
    'procs': procs,
    'devs': devs,
    **devs,
    **procs,
    **model_map
}

code.interact(local=local)

Now I find myself wanting to add settings, models, and several other Django objects that are already included with shell_plus, but I can't find a way to add local variables to the shell_plus session.

Brett Thomas's answer shows how to import modules into a shell_plus session, but doesn't show how to add variables from a dict-like object.

How do I add variables to a shell_plus session?

You can add the variables from your management command, like:

SHELL_PLUS_IMPORTS = [
    'my_app.management.commands.my_command import procs, devs',
    'from module.submodule2 import function3 as another1',
    'from module.submodule3 import *',
    'import module.submodule4',
]

This will then load the procs and devs from the my_command as variables in the shell.

Back to Top