【问题标题】:'Answer' instance needs to have a primary key value before a many-to-many relationship can be used'Answer' 实例需要有一个主键值才能使用多对多关系
【发布时间】:2010-10-24 18:23:03
【问题描述】:

我有一个名为Answer 的模型,它与另一个名为Question 的模型有ForeignKey 关系。这意味着问题自然可以有多个答案。

class Question(models.Model):
    kind = models.CharField(max_length=1, choices=_SURVEY_QUESTION_KINDS)
    text = models.CharField(max_length=256)

class Answer(models.Model):
    user = models.ForeignKey(User, related_name='answerers')
    question = models.ForeignKey(Question)
    choices = models.ManyToManyField(Choice, null=True, blank=True) # <-- !
    text = models.CharField(max_length=_SURVEY_CHARFIELD_SIZE, blank=True)

现在我正在尝试创建一个Answer 实例,然后将M2M 关系设置为Choice,但在接触M2M 之前出现以下错误:'Answer' instance needs to have a primary key value before a many-to-many relationship can be used.

 ans = Answer(user=self._request.user,
              question=self._question[k],
              text=v)
 ans.save() # [1]

当我注释掉 [1] 时,问题当然消失了,但我不明白为什么它首先出现,因为正如你所看到的,我在全部!


编辑:名称choices 似乎也没有问题。我尝试将它的每次出现都更改为options,但遇到了同样的问题。

【问题讨论】:

  • 恐怕这不会对我产生任何错误(你说得对,它不应该)。您的 Choice 模型是什么样的?任何自定义初始化、元类或继承?模块中您定义模型或实例化 Answer 的任何全局/局部变量都可能与选项或选项发生冲突(尽管我从您的编辑中注意到您可能已经想到了这一点)。跨度>
  • 或者自定义 save() 方法,也许,在您的 Answer 模型中?
  • 这对我来说实际上是个好消息,它对其他人有用。我会继续调查。
  • (不,我没有自定义的 save() 方法。)

标签: django django-models many-to-many


【解决方案1】:

感谢所有花时间回答这个问题的人。我的问题中提供的课程并不完整,因为我认为内部的 Meta 课程并不重要。事实上,Answer 看起来像这样:

class Answer(models.Model):
    """
    We have two fields here to represent answers to different kinds of
    questions.  Since the text answers don't have any foreign key to anything
    relating to the question that was answered, we must have a FK to the
    question.
    """

    class Meta:
        order_with_respect_to = 'options'

    def __unicode__(self):
        return '%s on "%s"' % (self.user, self.question)

    user     = models.ForeignKey(User, related_name='answers')
    question = models.ForeignKey(Question)
    options  = models.ManyToManyField(Option, blank=True)
    text     = models.CharField(max_length=_SURVEY_CHARFIELD_SIZE, blank=True)
    answered = models.DateTimeField(auto_now_add=True)

看看order_with_respect_to,你就会明白错误来自哪里。 :)

【讨论】:

    猜你喜欢
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多