Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF: custom ordering on related serializers

I've got two serializers one for an Instructor and one for a Course. The Instructor serializer has a defined relationship to the courses like so:

courses = CourseSerializer(many=True, read_only=True)

How do I specify an order to the courses in the instructor serializer?

Note: I have defined the ordering value in the Course Meta class, but it is the default sorting I want everywhere else. What I want is a custom ordering for api output (specifically dept, number, -semester rather than the default -semester).

like image 847
chadgh Avatar asked Oct 28 '15 21:10

chadgh


2 Answers

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
like image 124
TheAxeR Avatar answered Nov 16 '22 22:11

TheAxeR


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')))
like image 42
Endre Both Avatar answered Nov 16 '22 22:11

Endre Both