Created
July 8, 2019 07:36
-
-
Save akshar-raaj/939b6f988423f673162af0d813b2f873 to your computer and use it in GitHub Desktop.
QuestionSerializer with overridden create()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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