【问题标题】:How to remove nesting from Django REST Framework serializer?如何从 Django REST Framework 序列化程序中删除嵌套?
【发布时间】:2021-05-17 18:10:09
【问题描述】:

我的models.py 文件中定义了两个模型:

class Album(models.Model):
    album = models.CharField(max_length=100)
    band = models.CharField(max_length=100)

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    song = models.CharField(max_length=100)

对于这些,我在serializers.py 文件中将序列化程序定义为:

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = "__all__"


class SongSerializer(serializers.ModelSerializer):
    album = AlbumSerializer()
    class Meta:
        model = Song
        fields = "__all__"

当我发出请求时,我得到的数据是这样的格式:

[
    {
        "id": 1,
        "album": {
            "id": 1,
            "album": "Hybrid Theory",
            "band": "Linkin Park"
        },
        "song": "Numb"
    },
    {
        "id": 2,
        "album": {
            "id": 1,
            "album": "Hybrid Theory",
            "band": "Linkin Park"
        },
        "song": "In the End"
    }
]

如何从歌曲序列化器中删除专辑名称中的嵌套?我想要这样的数据:

[
    {
        "id": 1,
        "album_id": 1,
        "album": "Hybrid Theory",
        "band": "Linkin Park"
        "song": "Numb"
    },
    {
        "id": 2,
        "album_id": 1,
        "album": "Hybrid Theory",
        "band": "Linkin Park"
        "song": "In the End"
    }
]

【问题讨论】:

  • 您可以覆盖to_representation() 以获得您想要显示的数据的不同行为。

标签: django django-rest-framework


【解决方案1】:

SongSerializer

  1. 删除album = AlbumSerializer()

  2. 覆盖方法to_representation

from django.forms import model_to_dict

def to_representation(self, instance):
        song = super().to_representation(instance)
        album = model_to_dict(instance.album)
        for key, value in album.items():
           setattr(song, key, value)
        return song

我没有测试代码。

【讨论】:

    【解决方案2】:

    试试这个:

    class SongSerializer(serializers.ModelSerializer):
        album_id = serializers.SerializerMethodField(source='album.id')
        album = serializers.SerializerMethodField(source='album.album')
        band = serializers.SerializerMethodField(source='album.band')
    
        class Meta:
            model = Song
            fields = ['album_id', 'album', 'band', .....]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 2018-07-06
      • 1970-01-01
      • 2014-08-20
      • 2015-04-17
      • 1970-01-01
      相关资源
      最近更新 更多