30👍
✅
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
12👍
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')))
- [Django]-How to loop over form field choices and display associated model instance fields
- [Django]-Django REST Framework (DRF): Set current user id as field value
- [Django]-How to get username from Django Rest Framework JWT token
0👍
In this case you should modulate the ordering via the viewset queryset. I would imagine the following:
queryset = Instructor.objects.select_related('courses').order_by('courses__number')
👤Roba
- [Django]-A field with precision 10, scale 2 must round to an absolute value less than 10^8
- [Django]-405 "Method POST is not allowed" in Django REST framework
- [Django]-TypeError: data.forEach is not a function
-3👍
This should be doable simply by providing an ordered queryset
argument to your field declaration:
class InstructorSerializer(serializers.ModelSerializer):
courses = CourseSerializer(
queryset=Course.objects.order_by('...'),
many=True,
read_only=True,
)
Further details: http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument
- [Django]-Django celery task: Newly created model DoesNotExist
- [Django]-Are sessions needed for python-social-auth
- [Django]-Uninstall Django completely
Source:stackexchange.com