Elon Musk
Elon Musk

Reputation: 352

Rendering Foreign Key Elements from Django Rest Framework

I have the standard django polls models

class Poll(models.Model):

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.question_text

class Choice(models.Model):

    poll = models.ForeignKey(Poll, null=True, blank=True)
    choice_text = models.CharField(max_length=200)
    vote_count = models.IntegerField(default=0)

In the serialisers I have added a reference to foreign key as follows :

class PollSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(many=True, read_only=True, required=False)

    class Meta:
        model = Poll
        fields = ('id', 'question_text', 'pub_date', 'choices')

I have created the choices specific to the questions by the django admin. In the poll list from django rest framework, I expect to see the list of choices associated with the poll. It only shows the Poll objects as follows.

enter image description here

Can someone guide me, as to what has gone missing, and how can I see the choices associated with the Poll?

Upvotes: 0

Views: 454

Answers (2)

JPG
JPG

Reputation: 88529

Apart from @neverwalkaloner's answer, you could do it this way also,

class PollSerializer(serializers.ModelSerializer):
    choices_set = ChoiceSerializer(many=True, read_only=True, required=False)

    class Meta:
        model = Poll
        fields = ('id', 'question_text', 'pub_date', 'choices_set')

Upvotes: 2

neverwalkaloner
neverwalkaloner

Reputation: 47364

Since reverse manager for choice objects is choice_set You should set source='choice_set' for choices field:

class PollSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(many=True, read_only=True, required=False, source='choice_set')

Upvotes: 3

Related Questions