4

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

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 的内容:

设置.py:

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

模型.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

希望有人可以在这里帮助我。提前致谢!

4

2 回答 2

9

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

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

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

于 2012-06-01T14:25:24.470 回答
0

我猜你需要做

from dapp.dmodel.models import *

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

于 2012-05-31T19:33:13.593 回答