添加方法导入到shell_plus

Bre*_*mas 7 django django-extensions

shell_plus,有没有办法自动导入选定的辅助方法,如模型?

我经常打开shell来输入:

proj = Project.objects.get(project_id="asdf")
Run Code Online (Sandbox Code Playgroud)

我想用以下内容替换:

proj = getproj("asdf")
Run Code Online (Sandbox Code Playgroud)

Bre*_*mas 15

在文档中找到它.引自那里:

额外进口

除了导入模型之外,您还可以指定默认导入的其他项目.这些在SHELL_PLUS_PRE_IMPORTS和 中指定SHELL_PLUS_POST_IMPORTS.前者在任何其他导入之前导入(例如默认模型导入),后者在任何其他导入之后导入.两者都有类似的语法.所以在你的settings.py文件中:

SHELL_PLUS_PRE_IMPORTS = (
    ('module.submodule1', ('class1', 'function2')),
    ('module.submodule2', 'function3'),
    ('module.submodule3', '*'),
    'module.submodule4'
)
Run Code Online (Sandbox Code Playgroud)

上面的示例将直接转换为以下将在自动导入之前执行的python代码:

from module.submodule1 import class1, function2
from module.submodule2 import function3
from module.submodule3 import *
import module.submodule4
Run Code Online (Sandbox Code Playgroud)

shell启动后,这些符号将立即可用.

  • 如果您要导入一项,请不要忘记逗号:`SHELL_PLUS_PRE_IMPORTS = ('haystack',)` (2认同)

lal*_*alo 0

好的,有两种方法:

1)使用 PYTHONSTARTUP 变量(请参阅此文档

#in some file. (here, I'll call it "~/path/to/foo.py"

def getproj(p_od):
    #I'm importing here because this script run in any python shell session
    from some_app.models import Project
    return Project.objects.get(project_id="asdf")

#in your .bashrc
export PYTHONSTARTUP="~/path/to/foo.py"
Run Code Online (Sandbox Code Playgroud)

2)使用 ipython 启动(我最喜欢的)(请参阅此文档、此问题和此文档):

$ pip install ipython
$ ipython profile create
# put the foo.py script in  your profile_default/startup directory.
# django run ipython if it's installed. 

$ django-admin.py shell_plus 
Run Code Online (Sandbox Code Playgroud)