2

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

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]问题时,问题当然消失了,但我不明白为什么它首先出现,因为如您所见,我对 M2M 根本没有做任何事情!


编辑:名称似乎也不是问题choices。我尝试将其每次出现都更改options为相同的问题。

4

1 回答 1

2

感谢所有花时间在这个问题上的人。我的问题中提供的类不完整,因为我认为内部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你就会明白错误来自哪里。:)

于 2009-05-08T11:56:44.037 回答