I have 3 models. Question, Choice, and ChoiceColor.

class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    question= models.CharField(max_length=200)
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice = models.CharField(max_length=120)
    vote_count = models.IntegerField(default=0)
class ChoiceColor(models.Model):
    choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True)
    color = models.CharField(max_length=7)

I have a serializer that looks like this:


class CreateQuestionSerializer(serializers.ModelSerializer):
    choice_set = ChoiceSerializer(many=True)

    class Meta:
        model = Question
        fields = ('user', 'status', 'choice_set')

    def create(self, validated_data):
        choices_validated_data = validated_data.pop('choice_set')
        question = Question.objects.create(**validated_data)
        choices_serializer = self.fields['choice_set']

        for choice in choices_validated_data:
            choice['question'] = question

        choices_serializer.create(choices_validated_data)
        return question

And another that looks like this:

class ChoiceColorSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChoiceColor
        fields = ('color',)

class ChoiceSerializer(serializers.ModelSerializer):
    color_set = ChoiceColorSerializer(many=False)

    class Meta:
        model = Choice
        fields = ('choice', 'color_set')

For some reason, when I put in the data it does not work. I need to define 
a create method for ChoiceSerializer but i'm unsure how to do that?


-- 
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/778d4352-b2c0-4268-811f-24e3f8a5cd54%40googlegroups.com.

Reply via email to