我关注了这个link在我的 python 独立应用程序上使用 Django 的 ORM。 manage.py sql 'application_name' 和 manage.py syncdb 运行良好,并且在我执行 syncdb 时创建了表。我遇到的问题是当我运行将处理数据库事务的实际脚本(在本例中为 dparser.py)时,我遇到了“类型错误:相对导入需要‘包’参数”。以下是堆栈跟踪:
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
希望有人能帮我解决这个问题。提前致谢!
最佳答案
查看引发执行的 django.utils.importlib.py
代码,您会发现您的设置文件名导致了问题:
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
不要使用 .settings.py
作为设置文件的名称,使用不以“.”开头的名称它将解决这个特定错误。
关于python - 独立应用程序上的 Django ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837863/