Django Rest Framework序列化器关系:如何获取仅最新曲目的列表?

时间:2018-07-15 13:44:13

标签: python django serialization django-rest-framework

我正在关注本文档here。我正在努力使自己能够查询专辑对象,并使其只返回最新曲目而不是返回所有曲目。下面是文档模型和序列化器的修改版本。

模型

class AlbumOwner(models.Model):
    username = models.CharField(max_length=100)

class Album(models.Model):
    album_name = models.CharField(max_length=100)
    owner = models.ForeignKey(AlbumOwner, related_name='owner', on_delete=models.CASCADE)

class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)   

    class Meta:
        get_latest_by = 'created_at'

序列化器

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('title', 'created_at')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ('album_name', 'tracks')

我当前使用的查询如下,“ o”代表所有者:

albums = Album.objects.filter(owner=o)
serializer = AlbumSerializer(albums)
serializer.data

Serializer.data将返回类似于以下内容的响应:

[{
    'album_name': 'The Grey Album',
    'tracks': [
        {'title': 'Public Service Announcement', "created_at": "2018-06-15T06:22:35.680291Z"},
        {'title': 'What More Can I Say', "created_at": "2014-07-15T06:22:35.680291Z"},
        {'title': 'Encore', "created_at": "2016-07-15T06:22:35.680291Z"}
    ],
},{
    'album_name': 'The Blue Album',
    'tracks': [
        {'title': 'PSA', "created_at": "2002-07-15T06:22:35.680291Z"},
        {'title': 'WMCIS', '"created_at": "2003-07-15T06:22:35.680291Z"},
        {'title': 'E', "created_at": "2005-07-15T06:22:35.680291Z"}
    ],
},
]

我想要的响应是仅返回最新日期的曲目:

[{
        'album_name': 'The Grey Album',
        'tracks': [
            {'title': 'Public Service Announcement', "created_at": "2018-06-15T06:22:35.680291Z"}
        ],
    },{
        'album_name': 'The Blue Album',
        'tracks': [
            {'title': 'E', "created_at": "2005-07-15T06:22:35.680291Z"}
        ],
    },
    ]

1 个答案:

答案 0 :(得分:3)

请尝试以下类似方法,即对曲目查询集进行切片或根据某个过滤器选择最新的曲目。

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.SerializerMethodField()

    class Meta:
        model = Album
        fields = ('album_name', 'tracks')

    def get_tracks(self, album):
        qs = album.tracks.all()[-1:]
        return TrackSerializer(qs, many=True, read_only=True).data