簡體   English   中英

如何在 Django Rest Framework 中顯示 ManyToMany 字段的值而不是它們的 ID?

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

模型:

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 而不是值:

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

其中流派1. 流行3. 搖滾

我可以對 to_representation 進行哪些更改以打印值而不是流派的 id,流派是帶有歌曲模型的 ManyToManyField。

你快到了,試試這個

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

雖然上面的答案是正確的,但你也可以這樣做。

class SongSerializer(serializers.ModelSerializer):

    genre= serializers.StringRelatedField(many=True)

    class Meta:
       model = Song
       fields = '__all__'

https://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM