views:

708

answers:

1

I have a model called Answer which has a ForeignKey relationship to another model called Question. This means there can be several answers to question, naturally.

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)

Now I'm trying to create an Answer instance, and then set the M2M relationship to Choice, but I get the following error before even touching the 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]

When I comment out [1] the problem goes away of course, but I don't understand why it comes up in the first place, because as you can see, I'm doing nothing with the M2M at all!


EDIT: It doesn't seem to be a problem with the name choices either. I tried changing every occurence of it to options with the same problem.

+2  A: 

Thanks to everyone who took their time on this question. The classes provided in my question weren't complete, because I thought the inner Meta classes didn't matter. In fact, Answer looked like this:

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)

Take a look at order_with_respect_to and you'll understand where the error came from. :)

Deniz Dogan
Cool. Glad we could help.
Jarret Hardie