Shashishekhar Hasabnis
Shashishekhar Hasabnis

Reputation: 1766

How to create an in instance using HyperlinkedModelSerializer by just providing the url of the nested HyperlinkedModelSerializer fields?

I am trying to create an instance of a model which has all its fields to be the related fields.

class LearnerQuestionAnswer(models.Model):
    quiz_question = models.ForeignKey(Quiz_Question, on_delete=models.CASCADE)
    learner = models.ForeignKey(Learner_Model, on_delete=models.CASCADE)
    chosen_option = models.ForeignKey(Answer_Options, related_name="chosen_option", default=None, on_delete=models.CASCADE, blank=True, null=True)

For this model I have created the following serializer:-

class LearnerQuestionAnswerSerializer(serializers.HyperlinkedModelSerializer):
    quiz_question = Quiz_QuestionSerializer()
    learner = Learner_ModelSerializer()
    chosen_option = Answer_OptionsSerializer()
    class Meta:
        model = LearnerQuestionAnswer
        fields = ('quiz_question', 'learner', 'chosen_option')

All the nested serializer's are as well HyperlinkedModelSerializer.

I want to create an instance of this model by just providing the urls of the related fields like for example consider the following POST method:-

{
    "quiz_question":  "http://localhost:8080/api/registration_quiz_questions/83/",
    "learner":  "http://localhost:8080/api/registration_learners/3/",
    "chosen_option": "http://localhost:8080/api/registration_answer_options/218/",
}

Is this possible an how?

Upvotes: 2

Views: 256

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47374

HyperlinkedModelSerializerusing for related fields HyperlinkedRelatedField by default, which can give you desired behavior. To represent data as nested objects you can override to_representation method:

class LearnerQuestionAnswerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = LearnerQuestionAnswer
        fields = ('quiz_question', 'learner', 'chosen_option')

    def to_representation(self, instance):
        self.fields['quiz_question'] = Quiz_QuestionSerializer()
        self.fields['learner'] = Learner_ModelSerializer()
        self.fields['chosen_option'] = Answer_OptionsSerializer()
        return super(LearnerQuestionAnswerSerializer, self).to_representation(instance)

Upvotes: 2

Related Questions