亲爱的兄弟, 我非常喜欢Django ORM,所以我试图在Django Project之外使用它。但是当我尝试使用它时,我遇到了一个问题。 这是我在Mac上的文件结构:
testORM
|-- orm
|-- __init__.py
|-- models.py
|-- manage.py
|-- settings.py
|-- test.py
以下是我非常简单的代码:
models.py:
from django.db import models
class test(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table='test'
app_label='orm'
manage.py:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'Portal', # Or path to database file if using sqlite3.
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': 'Cloud', # Not used with sqlite3.
'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '5432', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
INSTALLED_APPS = (
'orm',
)
test.py:
import sys
sys.path.append('/Users/wally/Documents/workspace/testORM')
sys.path.append('/Users/wally/Documents/workspace/testORM/orm')
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import setup_environ
import settings
setup_environ(settings)
以下是我尝试从eclipse执行test.py时得到的内容:
Traceback (most recent call last):
File "/Users/wally/Documents/workspace/testORM/test.py", line 14, in <module>
setup_environ(settings)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 433, in setup_environ
import_module(project_name)
File "/Library/Python/2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named testORM
但是当我尝试执行时
python manage.py shell
from django.db import connection
cursor = connection.cursor()
他们都从命令行工作得很好!!!即使我创建模型的对象并保存数据也工作得很好,一切都通过shell工作正常。
答案 0 :(得分:1)
我创建了所有这些文件来复制您的环境,并且能够产生此错误。
在python test.py
文件夹中创建空__init__.py
文件时, testORM
开始工作。