Django Rest Framework嵌套模型作为列表而不是dict

时间:2015-12-08 02:31:43

标签: python django django-rest-framework

有没有办法让嵌套模型作为 List 而不是 Dict
我正在尝试使用 ListField 来实现它,但是很难 以下示例以更好地解释我正在尝试做什么。

样本模型:

class Album(models.Model):
    name = models.CharField(max_length=250)

class Track(models.Model):
    title = models.CharField(max_length=250)
    number = models.IntegerField()
    album = models.ForeignKey(Album, related_name="tracks")

示例序列化程序:

Class TrackSerializer(serializers.ModelSerializer):
    class Meta:
    model = Track
    fields = ['number', 'title']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)
    model = Album
    fields = ['name', 'tracks']

上述代码导致输出错误:

{
    "name": "ALBUM NAME",
    "tracks": [
        {
            "number": 1,
            "title": "TRACK TITLE"
        },
        {
            "number": 2,
            "title": "OTHER TRACK TITLE"
        }
    ]
}

期望的输出:

{
    "name": "ALBUM NAME",
    "tracks": [
        [1, "TRACK TITLE"],
        [2, "OTHER TRACK TITLE"]
    ]
}

1 个答案:

答案 0 :(得分:0)

解决方案:一个专辑序列化程序,其中一个字段是方法的结果,可以是任何字段( SerializerMethodField

<强> serializers.py

class AlbumSerializer(serializers.ModelSerializer):
    track_list = serializers.SerializerMethodField()
    class Meta:
        model = Album
        fields = ['name', 'track_list']
    class get_track_list(self, obj):
        output = []
        for i in Track.objects.filter(album = obj.id):
            output.append([i.number, i.title])
        return output

这会返回一个带有属性&#34; name&#34;的JSON。和&#34; track_list&#34;,就像我需要的那样:

{
    "name": "ALBUM NAME",
    "track_list": [
        [1, "TRACK TITLE"],
        [2, "OTHER TRACK TITLE"]
    ]
}