2
我想執行位於restaurants_project/scripts/
的seeds.py
腳本。這個種子文件將通過使用我的Django模型Restaurant
,根據同一文件夾中的CSV數據填充我的數據庫。我發現將項目設置(即restaurant_project.settings
)和我的必要模型一起包含在種子文件中的唯一方法是sys.path.append('MY_PROJECTS_RELATIVE_PATH')
。我顯然不希望這樣做在生產(或我?)有啥包括沒有得到這些設置的最佳方法如下ImportError
:如何在沒有相對項目路徑的子目錄中使用Django設置運行腳本
ImportError: Could not import settings 'restaurants_project.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named 'restaurants_project'
Directory Tree:
|___restaurants_project
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____settings.cpython-34.pyc
| |____settings.py
| |____urls.py
| |____wsgi.py
|____restaurants
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| | |____admin.cpython-34.pyc
| | |____models.cpython-34.pyc
| |____admin.py
| |____migrations
| | |______init__.py
| |____models.py
| |____tests.py
| |____views.py
|____scripts
| |______init__.py
| |______pycache__
| | |______init__.cpython-34.pyc
| |____restaurant_inspections_2014.csv
| |____seeds.py
| |____unique_restaurant_ids.txt
seeds.py:
import os, sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'restaurants_project.settings')
import django
django.setup()
import csv
csvfile = open('restaurant_inspections_2014.csv')
reader = csv.reader(csvfile)
headers = next(reader, None)
for row in reader:
print(row)
import pdb; pdb.set_trace()