为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Django Rest Framework 中显示 ManyToMany 字段的值而不是

如何在 Django Rest Framework 中显示 ManyToMany 字段的值而不是

扬帆大鱼 2023-09-12 20:03:07
模型: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


查看完整回答
反对 回复 2023-09-12
?
动漫人物

TA贡献1815条经验 获得超10个赞

虽然上面的答案是正确的,但你也可以这样做。


class SongSerializer(serializers.ModelSerializer):


    genre= serializers.StringRelatedField(many=True)


    class Meta:

       model = Song

       fields = '__all__'

查看完整回答
反对 回复 2023-09-12
  • 2 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信