Skip to content

Instantly share code, notes, and snippets.

@akshar-raaj
Created July 8, 2019 07:36
Show Gist options
  • Select an option

  • Save akshar-raaj/939b6f988423f673162af0d813b2f873 to your computer and use it in GitHub Desktop.

Select an option

Save akshar-raaj/939b6f988423f673162af0d813b2f873 to your computer and use it in GitHub Desktop.
QuestionSerializer with overridden create()
class QuestionSerializer(serializers.ModelSerializer):
choice_set = ChoiceSerializer(many=True)
class Meta:
model = Question
fields = '__all__'
def create(self, validated_data):
choice_validated_data = validated_data.pop('choice_set')
question = Question.objects.create(**validated_data)
choice_set_serializer = self.fields['choice_set']
for each in choice_validated_data:
each['question'] = question
choices = choice_set_serializer.create(choice_validated_data)
return question
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment