嵌套在序列化器中的序列化过滤器输出

时间:2019-01-28 14:06:38

标签: django django-rest-framework

在此示例中:

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

我如何定义我只想定序为1的曲目?

1 个答案:

答案 0 :(得分:0)

您可以尝试

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