在序列化程序中嵌套序列化筛选器输出



在这个例子中:

class TrackSerializer(serializers.ModelSerializer):
        class Meta:
        model = Track
        fields = ('order', 'title', 'duration')
class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)
    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

此输出发生:

'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
    {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
    {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
    {'order': 3, 'title': 'Encore', 'duration': 159},
enter code here

如何定义我只想要 orded:1 的曲目?

你可以试试

class AlbumSerializer(serializers.ModelSerializer): 
   tracks = TrackSerializer(many=True, queryset=Track.objects.filter(order=1))

最新更新