Django Rest-Framework nested serializer order

后端 未结 4 1841
我寻月下人不归
我寻月下人不归 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 01:55

    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')))
    

提交回复
热议问题