如何在Django中向具有多个外键的关系添加数据?
如何在Django中向具有多个外键的关系添加数据?
我正在用Python构建一个模拟程序,想用Django的ORM来把(中间和最终的)结果存储到数据库里。所以我不太关心网址和视图。
我遇到的问题是,如何创建一个包含多个外键的对象。这个对象应该表示一个代理和一个时间步骤之间的关系。
以下是我的代码:
我使用了以下模型:
from django.db import models
import random
from django.contrib.admin.util import related_name
# Create your models here.
class Agent(models.Model):
agent = int
def __init__(self, agent, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
self.agent = agent
def __str__(self):
return str(self.agent)
class Step(models.Model):
step = int
def __init__(self, step, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
self.step = step
def __str__(self):
return str(self.step)
class StepAgentData(models.Model):
def __init__(self, step, agent, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
self.step = step #This does not work
self.agent = agent
step = models.ForeignKey(Step, related_name='time_step')
agent = models.ForeignKey(Agent, related_name='associated_agent')
data = float
def __unicode__(self):
return str("Step %s \t Agent %s ", (self.step,self.agent))
运行以下脚本:
from DBStructureTest.App.models import Step, Agent, StepAgentData
if __name__ == '__main__':
s = Step(1)
s.save()
a = Agent(2)
a.save()
sad = StepAgentData(s,a)
sad.save()
print "finished"
在执行StepAgentData构造函数中的self.step = step时,会出现以下错误信息(请查看StepAgentData模型中的注释):
> File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py",
> line 367, in __set__
> val = getattr(value, self.field.rel.get_related_field().attname)
> File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py",
> line 773, in get_related_field
> data = self.to._meta.get_field_by_name(self.field_name) File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py",
> line 307, in get_field_by_name
> cache = self.init_name_map() File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py",
> line 337, in init_name_map
> for f, model in self.get_all_related_m2m_objects_with_model():
> File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py",
> line 414, in get_all_related_m2m_objects_with_model
> cache = self._fill_related_many_to_many_cache() File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py",
> line 428, in _fill_related_many_to_many_cache
> for klass in get_models(): File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py",
> line 167, in get_models
> self._populate() File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py",
> line 61, in _populate
> self.load_app(app_name, True) File
> "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py",
> line 76, in load_app
> app_module = import_module(app_name) File
> "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py",
> line 35, in import_module
> __import__(name) ImportError: No module named App
文件夹结构如下:
|-DBStructureTest
|-App
|-__init__.py
|-Main.py
|-models.py
|-test.py
|-views.py
|-__init__.py
|-manage.py
|-settings.py
|-urls.py
我哪里做错了?非常感谢任何帮助。
编辑:在/App目录下,我在执行'import models'后得到了以下信息:
import models Traceback (most recent call last): File "", line 1, in File "models.py", line 1, in from django.db import models File "/usr/local/lib/python2.7/dist-packages/django/db/init.py", line 14, in if not settings.DATABASES: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 276, in getattr self._setup() File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 40, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. '
2 个回答
首先,你可能想为StepAgent类使用多对多关系。这种关系可以让一个对象和多个对象相互关联。你还可以在多对多关系中添加一些额外的字段,这样设计会更好。
关于你的错误,你需要执行 export DJANGO_SETTINGS_MODULE=settings
,或者确保当前的 PYTHONPATH
可以找到你的设置模块。否则,Django就不知道在哪里找到你的设置,也不知道该如何配置它。
这其实是两个不同的问题。第一个问题是因为你似乎是在DBStructureTest这个文件夹里运行你的脚本,所以它在尝试找这个文件夹下面的DBStructureTest子文件夹。第二个问题就比较简单明了了,你需要设置环境变量或者运行“manage.py shell”。
顺便说一下,我在你的模型里没有看到任何数据库字段。对应的SQL表里有数据吗?