I have a Question Model with a ForeignKey field (answer) and a 
ManyToManyField (choices) that link to the same model (Choice).

When I create a question I create a new Choice object for the answer field 
but that option does not show up for the choices field.

I don't want to have to cancel the creation of a Question so that I can 
select the same Choice object for both answer and choices.

So I either need the choices field to have the Choice option created form 
the answer field or I need to make sure that the answer Choice is an option 
in the choices field.

#models.pyclass Choice(models.Model):
    choice = models.CharField(max_length=64)
    def __unicode__(self):
        return self.choice
#multiple choice questionclass Question(models.Model):
    question = models.CharField(max_length=64)
    answer = models.ForeignKey('Choice', related_name='is_answer_for')
    choices = models.ManyToManyField(Choice, related_name='questions', 
verbose_name='other choices')
    module = models.ForeignKey('Module', related_name='questions')

    times_correct = models.IntegerField(editable=False, default=0)
    times_total = models.IntegerField(editable=False, default=0)

    def _get_average(self):
        "Returns the average in percent"
        if self.times_total != 0:
            return (self.times_correct / float(self.times_total))*100
        return 0.0
    average = property(_get_average)

    def save(self, *args, **kwargs):
        super(Question, self).save(*args, **kwargs)
        #make sure that the answer is also in choices
        if self.answer not in self.choices.all():
            self.choices.add(self.answer)
        super(Question, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.question
#The code should work>>> from quiz.models import *>>> q = 
Question.objects.get(id=1)

#I created q with the above model and as you can see it doesn't work>>> print 
q.answer not in q.choices.all()True>>> q.choices.add(q.answer)>>> print 
q.answer not in q.choices.all()False


I added the save above because it complained that the question field needed to 
have a value, which I don't really understand because it is a CharField

"needs to have a value for field "question" before this many-to-many 
relationship can be used."

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to