5

请注意以下 Django(1.4.3) 项目中的settings/dev.py而不是一个settings.py文件和script.pyin :my_app

.
├── my_project
│   ├── my_app
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── tests.py
│   │   ├── views.py
│   │   └── script.py
│   ├── __init__.py
│   ├── settings
│   │   ├── dev.py
│   │   ├── __init__.py
│   │   └── prod.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── requirements.txt

当我只有一个settings.py文件代替设置文件夹时,我能够运行以下脚本而没有任何错误

脚本.py:

###################################################################
# set up for making it possible to run a model query from my script. 
###################################################################
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from django.core.management import setup_environ
import settings
setup_environ(settings)
####################################################################  
from my_app.models import MyModel

all_entries = MyModel.objects.all()

顺便说一句,我从本文的第二种方法中得到了这一点,我的设置要长几行,因为我script.py的设置在my_app文件夹中,而不是直接在my_project文件夹下。

因为我现在正在使用我将脚本中设置的最后两行更改settings/dev.py insteadsettings.py以下内容:

import settings.dev
import setup_environ(settings.dev)

但是当我现在运行我的脚本时,我得到了这个错误:

Traceback (most recent call last):
  File "my_script.py", line 12, in <module>
    all_entries = MyModel.objects.all()
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/manager.py", line 131, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/query.py", line 358, in get
    clone = self.filter(*args, **kwargs)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/query.py", line 624, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/query.py", line 642, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q
    can_reuse=used_aliases, force_having=force_having)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1122, in add_filter
    process_extras=process_extras)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1304, in setup_joins
    field, model, direct, m2m = opts.get_field_by_name(name)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/options.py", line 311, in get_field_by_name
    cache = self.init_name_map()
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/options.py", line 341, in init_name_map
    for f, model in self.get_all_related_m2m_objects_with_model():
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/options.py", line 429, in get_all_related_m2m_objects_with_model
    cache = self._fill_related_many_to_many_cache()
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/options.py", line 443, in _fill_related_many_to_many_cache
    for klass in get_models(only_installed=False):
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/loading.py", line 181, in get_models
    self._populate()
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/loading.py", line 64, in _populate
    self.load_app(app_name, True)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/db/models/loading.py", line 86, in load_app
    app_module = import_module(app_name)
  File "/home/my_username/.virtualenvs/my_project/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named my_project.my_app

为什么会出现这个错误?如何使用而不是在 Django 中运行我的脚本?settings/dev.pysettings.py

4

1 回答 1

9

如果您只想在 django 环境中运行脚本,那么完成此操作的最简单方法是创建一个./manage.py子命令,如下所示

from django.core.management.base import BaseCommand
from my_app.models import MyModel

class Command(BaseCommand):
    help = 'runs your code in the django environment'

    def handle(self, *args, **options):
        all_entries = MyModel.objects.all()
        for entry in all_entries:
            self.stdout.write('entry "%s"' % entry)

文档对解释这一点很有帮助。

但是,您可以指定要使用的设置文件运行

$ django-admin.py runserver --settings=settings.dev

它将使用其中的设置运行测试服务器,dev但我担心您的问题比简单的问题更深层次。我不建议更改manage.py文件,因为这会导致不一致和未来的麻烦。

另请注意,dev.py如果您要这样做,它应该是一个完整的设置文件。我个人会推荐这样的结构:

|-settings
|    |- __init__.py
|    |- base.py
|    |- dev.py
|    |- prod.py

并保留您的所有常规设置,并将您的etcbase.py的第一行更改为类似dev.py

# settings/dev.py
from .base import *

DEBUG = True
...

编辑

如果您只是想测试一下,为什么不尝试

$ ./manage.py shell

或使用您的开发设置

$ django-admin.py shell --settings=settings.dev

因为这将为您设置所有操作系统环境变量,settings.py然后您可以测试/调试

>>> from my_app.models import MyModel
>>> all_entries = MyModel.objects.all()
>>> for entry in all_entries:
...   print entry    
于 2013-01-30T12:06:38.943 回答