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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With