Add extra field to ModelSerializer

Viewed 121

I want to make a quiz app and I have two models that looks like this:

class Question(models.Model):
 question = models.CharField(max_length=100)

class Answer(models.Model):
 answer = models.CharField(max_length=30)
 is_true = models.BooleanField(default=False)
 question = models.ForeignKey(Question, on_delete=models.CASCADE)

Now I want to create a ModelSerializer that contains the question and the answes related. Something like this:

[
 {
   'question': 'Something',
   'answers': [
     'something1', 'something2', 'something3' 
    ]
 }
]

The problem that I face is that the ForeignKey is in the Answer model not in the Question model.

How can I add the Answers in the Question model? Thanks

1 Answers

It is likely better to rename the relation in reverse from answer_set to answers, this makes it more consistent between serializers and models:

class Answer(models.Model):
    answer = models.CharField(max_length=30)
    is_true = models.BooleanField(default=False)
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='answers'
    )

You can serialize the answers with a SlugRelatedField [drf-doc]:

class QuestionSerializer(serializers.ModelSerializer):
    answers = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='answer'
     )

    class Meta:
        model = Question
        fields = ['question', 'answers']
Related