2

という別のモデルと関係がある というモデルがAnswerあります。これは、当然のことながら、質問に対するいくつかの答えが存在する可能性があることを意味します。ForeignKeyQuestion

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 で何もしていないからです。


編集:名前にも問題はないようですchoicesoptions同じ問題で、すべての発生をに変更してみました。

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 に答える