NameError:名称“ Recipe”未定义

时间:2018-12-28 14:47:39

标签: django

我正在尝试使用以下命令在Django中运行脚本:

python manage.py shell < recipes/launch_bundle.py

脚本如下:

from recipes.models import Recipe

def create_bundle(recipe_id):
    rec = Recipe.objects.get(pk=recipe_id)
    print('done')

create_bundle(1)

请注意第一行-应该导入模型Recipe。运行时,出现错误:

Traceback (most recent call last):
File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 92, in handle
    exec(sys.stdin.read())
File "<string>", line 7, in <module>
File "<string>", line 4, in create_bundle
NameError: name 'Recipe' is not defined

我很困惑,因为我清楚地导入了Recipe,并且进一步,因为我可以使用 python manage.py shell 启动shell,然后复制粘贴代码即可正常工作。

这是什么问题?为什么我的代码在shell中运行正常,但在作为脚本调用时却运行不正常?

请注意,我已经研究了other questions,但他们似乎都说:您尚未导入模型或类似的东西

0 个答案:

没有答案