如何显示Django Rest Framework中的ManyToMany字段的值而不是其ID? [英] How can I display the values of a ManyToMany Field in Django Rest Framework instead of their Ids?

查看:155
本文介绍了如何显示Django Rest Framework中的ManyToMany字段的值而不是其ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号:

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)

序列化器:

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而非值:

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
        ]
    }
]

其中类型 1。弹出 3。 Rock

我可以对to_representation进行哪些更改以打印值,而不是流派的ID(即带有Song Model的ManyToManyField的流派ID)。

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.

推荐答案

您快到了,试试这个

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

这篇关于如何显示Django Rest Framework中的ManyToMany字段的值而不是其ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆