django 脚本中的Python导入模块不起作用

yzxexxkh  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(170)
import json
import os
import django
import openai
import sys

# Ensure the DJANGO_SETTINGS_MODULE is set to your project's settings module.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tastify_backend.settings")
django.setup()

from recipe.models import Ingredient, IngredientCategory, MeasuringUnit, Recipe

print(Ingredient.objects.all().select_related('ingredient_category').filter(ingredient_category=1))

字符串
模型的导入不起作用,有以下几种情况:
这里是错误追溯,这样你就可以检查我错过了什么。

Traceback (most recent call last):
  File "/Users/patrickvogele/Desktop/tastify_backend/recipe/scripts/generate_ingredients.py", line 9, in <module>
    django.setup()
  File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 102, in __getattr__
    self._setup(name)
  File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 89, in _setup
    self._wrapped = Settings(settings_module)
  File "/Users/patrickvogele/Desktop/tastify_backend/tastify_env/lib/python3.9/site-packages/django/conf/__init__.py", line 217, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tastify_backend'


的数据
为什么会这样?

waxmsbnn

waxmsbnn1#

我解决了这个问题-这不是关于tastify_backend.py文件,而是关于设置。
在运行脚本和django设置之前,我需要添加tastify后端的directory_path:

import json
import os
import openai
import sys
import django
import sys

# Add the directory to the sys.path
directory_path = '/Users/patrickvogele/Desktop/tastify_backend'
sys.path.append(directory_path)

# Now you can import modules and packages from the specified directory

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tastify_backend.settings")
django.setup()

字符串

相关问题