0

I want to create this kind of API Django:

 {
    question_no: "1",
    question: "How many sides are equal in a scalene triangle?",
    options:    [
        { answer_options: "3", selected: false, isCorrect: true },
        { answer_options: "2", selected: false, isCorrect: false},
        { answer_options: "0", selected: false, isCorrect: false},
        { answer_options: "1", selected: false, isCorrect: false},
    ],
},

but I don't know how can I add the options array in my API in the Django rest framework.

this is the model that I have created so far but it only contains question_no and question:

class quiz(models.Model):
    question_no = models.IntegerField()
    question = models.CharField(max_length=400)

how can I add the options array in my model?

1 Answer 1

1

If you have a model for options, you can do that using nested serializers like this:

class OptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Option
        fields = ('answer_options', 'selected', 'isCorrect', )

class QuizSerializer(serializers.ModelSerializer):
    options = OptionSerializer(many=True)
    class Meta:
        model = Quiz
        fields = ('question_no', 'question', 'options', )

if you don't have any model for that, you can use SerializerMethodField like this:

class QuizSerializer(serializers.ModelSerializer):
    options = SerializerMethodField(method_name=get_options)

    class Meta:
        model = Quiz
        fields = ('question_no', 'question', 'options', )

    def get_options(self, obj):
        # now you should get your list of options somehow, for example get it from object:
        # options = obj.get_options()
        # for simplicity, I just statically created options list:
        options = [
            { answer_options: "3", selected: False, isCorrect: True },
            { answer_options: "2", selected: False, isCorrect: False},
            { answer_options: "0", selected: False, isCorrect: False},
            { answer_options: "1", selected: False, isCorrect: False},
        ]
        return options
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.