在可以使用多对多关系之前,'Answer'实例需要具有主键值

时间:2009-05-08 10:40:39

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

我有一个名为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

1 个答案:

答案 0 :(得分: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,您就会明白错误的来源。 :)