Home > Net >  How to have a array inside an object in django rest framework api
How to have a array inside an object in django rest framework api

Time:02-27

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?

CodePudding user response:

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
  • Related