Django多对多关系 - 数据库“无”?

时间:2016-02-23 07:31:01

标签: django python-3.5

过去两个小时左右,我一直在抨击这个问题,并且想知道是否有人可以帮助我。使用此代码:

ann = Announcement(**params)
ann.save()
# Push this announcement to each competitor's unread announcements queue
for competitor in Competitor.objects.all():
    competitor.unread_announcements.add(ann)
    #ann.competitor_set.add(competitor)

以及相关的模型字段:

class Announcement(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=80, blank=False)
    body = models.TextField(blank=False)
    posted = models.DateTimeField(auto_now_add=True)
# ...
class Competitor(models.Model):
    id = models.AutoField(primary_key=True)
    unread_announcements = models.ManyToManyField('Announcement')

当我们到达将队列添加公告的行时,我们收到此错误:

Traceback (most recent call last):
  File "./manage.py", line 16, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python3.5/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python3.5/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/home/cam/Documents/Programming/web/pactf-web2/django/ctflex/management/commands/announce.py", line 40, in handle
    ann.competitor_set.add(competitor)
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 843, in add
    self._add_items(self.source_field_name, self.target_field_name, *objs)
  File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 963, in _add_items
    (obj, self.instance._state.db, obj._state.db)
ValueError: Cannot add "<Competitor: <Competitor #1 'cam'>>": instance is on database "None", value is on database "default"

我对该主题的所有研究表明,当一个或两个相关对象尚未保存在数据库中时,会导致此错误。但是,在这种情况下,我实际上预先将公告保存两行,而竞争对手已经存在于数据库中。那么,我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试省略模型的id字段。因为你注意到使用了Django提供的默认id。