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 REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-rest-framework/11ddcb9c-6175-4af6-b721-6cefba0c890e%40googlegroups.com.