如何在没有相对项目路径的子目录中使用Django设置运行脚本

时间:2015-04-16 19:36:46

标签: python django python-3.x django-models

我想执行seeds.py中的restaurants_project/scripts/脚本。此种子文件将使用我的Django模型Restaurant基于同一文件夹中的CSV数据使用餐馆记录填充我的数据库。我发现包含项目设置(即restaurant_project.settings)和我的必要模型的唯一方法是在种子文件中sys.path.append('MY_PROJECTS_RELATIVE_PATH')。我显然不想在制作中这样做(或者我呢?)那么在不获得以下ImportError的情况下包含这些设置的最佳方法是什么:

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()

1 个答案:

答案 0 :(得分:3)

编写使用项目设置的脚本的最佳方法是编写自定义管理命令:

https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/

基本上,您应该将脚本包装在扩展BaseCommand的类中,并将其放在应用程序的management/commands目录中。