【问题标题】:How can I display the values of a ManyToMany Field in Django Rest Framework instead of their Ids?如何在 Django Rest Framework 中显示 ManyToMany 字段的值而不是它们的 Id?
【发布时间】:2020-09-26 14:57:31
【问题描述】:

型号:

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 进行哪些更改以打印值而不是 Genre 的 id,后者是带有 Song Model 的 ManyToManyField。

【问题讨论】:

    标签: python django-rest-framework


    【解决方案1】:

    你快到了,试试这个

    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

    【讨论】:

      【解决方案2】:

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

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 2021-03-04
        • 1970-01-01
        • 2017-03-25
        • 2019-04-01
        • 2021-01-10
        • 2023-03-05
        相关资源
        最近更新 更多