Django Rest-Framework nested serializer order

后端 未结 4 1840
我寻月下人不归
我寻月下人不归 2021-02-05 01:40

Is there a way to order a nested serializer _set, for example order by pk or time-stamp.

So basically order song_set

4条回答
  •  温柔的废话
    2021-02-05 02:10

    You can use SerializerMethodField and write custom method for this.

    class AlbumSerializer(HyperlinkedModelSerializer):
        song_set = serializers.SerializerMethodField()
        class Meta:
            model = Album
            fields = [
                'pk',
                'timestamp',
                'song_set'
            ]
    
        def get_song_set(self, instance):
            songs = instance.song_set.all().order_by('-timestamp')
            return SongListSerializer(songs, many=True).data
    

提交回复
热议问题