Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display the values of a ManyToMany Field in Django Rest Framework instead of their Ids?

Model:

class Genre(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Song(models.Model):
    name = models.CharField(max_length=200)
    genre = models.ManyToManyField(Genre)

Serializers:

class GenreSerializer(serializers.ModelSerializer):

    class Meta:
        model = Genre
        fields = '__all__'


class SongSerializer(serializers.ModelSerializer):

    class Meta:
        model = Song
        fields = '__all__'

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        print(GenreSerializer(instance.name).data)
        return rep

The above print in serializer gives: {'name': None} and the response is with the Genre ids instead of values:

[
    {
        "id": 1,
        "name": "Abcd",
        "genre": [
            1,
            3
        ]
    }
]

where genre 1. Pop and 3. Rock

What changes can I make to to_representation to print the values instead of the ids of Genre which is a ManyToManyField with Song Model.

like image 888
codecrazy46 Avatar asked Dec 06 '25 06:12

codecrazy46


1 Answers

You were almost there, try this

class SongSerializer(serializers.ModelSerializer):
    class Meta:
        model = Song
        fields = '__all__'

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep["genre"] = GenreSerializer(instance.genre.all(), many=True).data
        return rep
like image 71
JPG Avatar answered Dec 07 '25 22:12

JPG