Is there a way to order a nested serializer _set
, for example order by pk
or time-stamp
.
So basically order song_set
Old thread, but because it's still popping up on Google I want to share my answer as well. Try overwriting the Serializer.to_representation
method. Now you can basically do whatever you want, including customising the sorting of your response. In your case:
class AlbumSerializer(HyperlinkedModelSerializer):
song_set = SongListSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = [
'pk',
'timestamp',
'song_set'
]
def to_representation(self, instance):
response = super().to_representation(instance)
response["song_set"] = sorted(response["song_set"], key=lambda x: x["timestamp"])
return response