Amr Ragaey
Amr Ragaey

Reputation: 1103

Django Rest Framework- Writable nested serializers error

I'm trying to create a quiz app, i'm a beginner in dajango and rest, and I'm trying to create a serializer for creating new question with choices, i also not understand well how writable nested serializers working, if some one can give a working example

models.py:

class Question(models.Model):
    quiz = models.ForeignKey(Quiz, related_name="question")
    question = models.CharField(max_length=200)

    def __unicode__(self):
        return self.question 

class Choice(models.Model):
    question = models.ForeignKey(Question, related_name="choice")
    choice = models.CharField(max_length=200)
    correct_answer = models.BooleanField(default=False)

    def __unicode__(self):
        return self.choice

serializers.py:

class createChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('choice','correct_answer',)

class createQuestionSerializer(serializers.ModelSerializer):
    choices = createChoiceSerializer()
    class Meta:
        model = Question

    def create(self, validated_data):
        choices_data = validated_data.pop('choices')
        question = Choice.objects.create(**validated_data)
        for choice in choices_data:
            try:
                choice = Choice.objects.get(name=choice["name"])
            except Choice.DoesNotExist:
                choice = Choice.objects.create(**choice)
            question.choices.add(choice)
        return question

when i write the question and choice i got an error: ValueError at /questions/create

Cannot assign "u"what's your name"": "Choice.question" must be a "Question" instance.

Upvotes: 3

Views: 546

Answers (1)

brsbilgic
brsbilgic

Reputation: 11843

question = Choice.objects.create(**validated_data)

question is a Choice instance and question.choices.add(choice) basically adds Choice to Choice instance.

You may try Question.objects.create(**validated_data). I'm not sure if this works but at least solves the error you encounter now.

Upvotes: 1

Related Questions