模型:class Genre(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.nameclass Song(models.Model): name = models.CharField(max_length=200) genre = models.ManyToManyField(Genre)序列化器: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序列化程序中的上述打印给出: {'name': None} 并且响应使用流派 ID 而不是值:[ { "id": 1, "name": "Abcd", "genre": [ 1, 3 ] }]其中流派1. 流行,3. 摇滚我可以对 to_representation 进行哪些更改以打印值而不是流派的 id,流派是带有歌曲模型的 ManyToManyField。
2 回答
倚天杖
TA贡献1828条经验 获得超3个赞
你就快到了,试试这个
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
动漫人物
TA贡献1815条经验 获得超10个赞
虽然上面的答案是正确的,但你也可以这样做。
class SongSerializer(serializers.ModelSerializer):
genre= serializers.StringRelatedField(many=True)
class Meta:
model = Song
fields = '__all__'
添加回答
举报
0/150
提交
取消