关于独立应用程序的Django ORM

时间:2012-05-31 16:49:13

标签: python django orm

我跟着这个link在我的独立应用程序中使用Django的ORM在python中。 manage.py sql'application_name'和manage.py syncdb运行良好,并且在执行syncdb时创建了表。我遇到的问题是当我运行将处理数据库事务的实际脚本(对于本例,它是dparser.py)时,我遇到了“TypeError:相对导入需要'package'参数”。下面是stacktrace:

Traceback (most recent call last):
  File "dparser.py", line 23, in <module>
    from dmodel.models import *
  File "/home/<user>/d/dapp/dmodel/models.py", line 1, in <module>
    from django.db import models
  File "/usr/local/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module>
    if DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner
    self._setup()
  File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 93, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 28, in import_module
    raise TypeError("relative imports require the 'package' argument")
TypeError: relative imports require the 'package' argument

以下是我的settings.py,models.py和dparser.py:

的内容

settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',   
        'NAME': 'd',
        'USER': 'root',
        'PASSWORD': '<password>',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}
INSTALLED_APPS = ("dapp.dmodel",)

models.py:

from django.db import models
from django.db.models import Max


class Topics(models.Model):
     topic_id = models.AutoField(primary_key=True)
     topic = models.CharField(max_length=1000)

class Links(models.Model):
     link_id = models.AutoField(primary_key=True)
     topic = models.ForeignKey(Topics)
     link = models.CharField(max_length=1000)

def getLastId(tag):
     ...
     return lastid

dparser.py(部分):

from django.conf import settings
os.environ['DJANGO_SETTINGS_MODULE'] = ".settings.py"
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',   
        'NAME': 'd',
        'USER': 'root',
        'PASSWORD': '<password>',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}
INSTALLED_APPS = ("dapp.dmodel",)

from dmodel.models import * # --> This is were the exception occurs

希望有人可以帮助我。提前谢谢!

2 个答案:

答案 0 :(得分:8)

查看引发execption的django.utils.importlib.py代码,您会看到您的设置文件名导致问题:

if name.startswith('.'):
    if not package:
        raise TypeError("relative imports require the 'package' argument")

请勿使用.settings.py作为设置文件的名称,请使用不以“。”开头的内容。它将解决这个特殊的错误。

答案 1 :(得分:0)

我猜你需要做

from dapp.dmodel.models import *

或设置PYTHONPATHsys.path以包含dapp文件夹。