Reputation: 1756
I am working with the nested serializers in my project. There is just one small problem that I am facing and unable to guess whats going wrong.
I have two models:-
Model 1:-
class Answer_Options(models.Model):
text = models.CharField(max_length=200)
Model 2:-
class Quiz_Question(models.Model):
text = models.CharField(max_length=200)
possible_answers = models.ManyToManyField(Answer_Options)
correct = models.ForeignKey(Answer_Options, related_name="correct", default=None, on_delete=models.CASCADE, blank=True, null=True)
I have created the following serializers for my above models as follows:-
class Answer_OptionsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Answer_Options
fields = ('url', 'text')
And for Quiz Question:-
class Quiz_QuestionSerializer(serializers.HyperlinkedModelSerializer):
possible_answers = Answer_OptionsSerializer(many=True)
correct = Answer_OptionsSerializer()
class Meta:
model = Quiz_Question
fields = ('url', 'text', 'possible_answers', 'correct')
def create(self, validated_data):
possible_answers_data = validated_data.pop('possible_answers')
correct_answers_data = validated_data.pop('correct')
quiz_question = Quiz_Question.objects.create(**validated_data)
if possible_answers_data:
for answer in possible_answers_data:
answer, created = Answer_Options.objects.get_or_create(text=answer['text'])
if (answer.text == correct_answers_data['text']):
quiz_question.correct = answer //Not sure why this is not getting saved
quiz_question.possible_answers.add(answer)
return quiz_question
What happens is that when I post data through Django Rest Framework the create method gets called and possible answers get saved but don't know why the correct answer is not getting save for that instance.
I am not getting any error or exception. Also I can see the correct answer on the Django Rest Frameworks new object created page. But when I click the details page for that object I see null value for the correct answer.
Any clue of what I am doing wrong?
The sample json data that I am posting is like:-
{
"text": "Google Headquarters are in?",
"possible_answers": [
{
"text": "USA"
},
{
"text": "Nort Korea"
},
{
"text": "China"
},
{
"text": "India"
}
],
"correct": {
"text": "USA"
}
}
Upvotes: 0
Views: 334
Reputation: 47354
You need to call save()
after changed correct
value:
def create(self, validated_data):
possible_answers_data = validated_data.pop('possible_answers')
correct_answers_data = validated_data.pop('correct')
quiz_question = Quiz_Question.objects.create(**validated_data)
if possible_answers_data:
for answer in possible_answers_data:
answer, created = Answer_Options.objects.get_or_create(text=answer['text'])
if answer.text == correct_answers_data['text']:
quiz_question.correct = answer
quiz_question.save() # save changes
quiz_question.possible_answers.add(answer)
return quiz_question
Upvotes: 2