DRF: custom ordering on related serializers
Since Django 1.7, you can specify a queryset for prefetch_related
. Using prefetch incurs just one additional database query instead of one per parent object with SerializerMethodField
.
from rest_framework import viewsets
from django.db.models import Prefetch
class InstructorViewSet(viewsets.ModelViewSet):
queryset = Instructor.objects.prefetch_related(Prefetch(
'courses',
queryset=Course.objects.order_by('dept', 'number')))
Since it is read only, wouldn't it be just as easy to use a serializer method for that field?
class InstructorSerializer(serializers.ModelSerializer):
courses = serializers.SerializerMethodField()
def get_courses(self, obj):
ordered_queryset = <do your magic here>
return CourseSerializer(ordered_queryset, many=True, context=self.context).data