Django Rest-Framework nested serializer order
In your ViewSet
, you can specify a queryset with a custom Prefetch
object that you can filter and order as you like. Prefetching causes just one additional database query (instead of one per parent object when using SerializerMethodField
), giving vastly improved performance.
from rest_framework import viewsets
from django.db.models import Prefetch
class AlbumViewSet(viewsets.ModelViewSet):
queryset = Album.objects.prefetch_related(Prefetch('song_set',
queryset=Song.objects.order_by('-timestamp')))
Add ordering meta parameter to your Song model:
class Song(models.Model):
album = models.ForeignKey('album.Album', default=1)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
class Meta:
ordering = ['timestamp', 'pk']
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