为此,我结合使用 2 个答案,提出了一种简单的单行方法。
您可以使用 -c 运行 django shell,它将运行您传递的命令,但是在代码运行后它会立即退出。
诀窍是设置您需要的内容,运行 code.interact(local=locals()) 然后从您传递的代码中重新启动 shell。像这样:
python manage.py shell -c 'import uuid;test="mytestvar";import code;code.interact(local=locals())'
对我来说,我只想要丰富库的检查方法。只有几行:
python manage.py shell -c 'import code;from rich import pretty;pretty.install();from rich import inspect;code.interact(local=locals())'
最后上面的樱桃是一个别名
alias djshell='python manage.py shell -c "import code;from rich import pretty;pretty.install();from rich import inspect;code.interact(local=locals())"'
现在,如果我启动我的 shell 并说,想要检查表单类,我会得到这个漂亮的输出:
