Django / DRF – Get field of a related model

Issue

everyone.
What I want is get field of a related model by serializer.
I have 2 models:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    def __str__(self):
        return self.question_text    



class Test(models.Model):
    test_name = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    question = models.ManyToManyField(Question, related_name='tests')
    def __str__(self):
        return self.test_name

Why I’ve used ManyToManyField?
Because I’ve followed here:
https://medium.com/django-rest/lets-build-a-basic-product-review-backend-with-drf-part-1-652dd9b95485

Now I can do smth like:
enter image description here

But I want get question_text in response.
What I tried:

class TestSerializer(serializers.HyperlinkedModelSerializer):
    question_text = serializers.CharField(read_only=True, source="question.question_text")
    class Meta:
        model = Test
        fields = ['pk', 'test_name', 'pub_date', 'question_text']
        expandable_fields = {
 'question': (QuestionSerializer, {'many': True})
}

But it returned:

enter image description here

I understand, that problem might be in DB relations, but I can’t get it.
Thanks in advance!

Solution

Use nested serializer:

class QuestionSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Question
        fields = ['question_text']

class TestSerializer(serializers.ModelSerializer):
    question = QuestionSerializer(many=True)
    class Meta:
        model = Test
        fields = ['pk', 'test_name', 'pub_date', 'question']

Answered By – Amin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published