I am getting a JSON input with the fields description
and choices
for a Question
model. The Choice
model also has a foreign key field pointing to Question
with a related name of choices
. However, in the JSON, the Choice
will come without the question_id
field, in order to be assigned after the creation of the Question
I am getting all kind of errors when trying to create a Question
and then assigning all incoming to it. Searched a lot for the error Direct assignment to the forward side
and didn’t found anything that solves my problem
I can’t change the related name and the JSON input fields, if this was a possibility I’d have already done it
class CreateQuestionSerializer(serializers.ModelSerializer):
description = serializers.CharField(max_length=1024, allow_blank=False, required=True)
choices = CreateChoiceSerializer(many=True, required=True)
def create(self, validated_data):
choices = validated_data.pop('choices')
question = Question.objects.create(**validated_data)
choices_serializer = CreateChoiceSerializer(data=choices, many=True, context={'question': question})
if choices_serializer.is_valid():
choices_serializer.save()
return question