DRF:在相关的序列化程序上的自定义排序 [英] 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)
如何在教师序列化程序中为课程指定顺序?
注意:我已经在Course Meta类中定义了 ordering
值,但这是我希望在其他所有地方使用的默认排序方式.我想要的是api输出的自定义排序(特别是dept,number,-semester,而不是默认的-semester).
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).
推荐答案
由于它是只读的,在该字段中使用序列化方法不是一样容易吗?
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
这篇关于DRF:在相关的序列化程序上的自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!