Django Rest Order on custom field from serializer?

I am trying to use Django Rest to return a json representation of a model based on an order from a custom field that is not bound to the model but attached to the serializer. I know how to do this with specific model fields, but how do you use django rest to return an order when the field is only in the serializer class? I want to return a list of photos ordered by "rating". Thank!

------ Views.py

class PicList(generics.ListAPIView):
    queryset = Pic.objects.all()
    serializer_class = PicSerializerBasic
    filter_backends = (filters.OrderingFilter,)
    ordering = ('score')

------ Serializer.py

class PicSerializer(serializers.ModelSerializer):
    userprofile = serializers.StringRelatedField()
    score = serializers.SerializerMethodField()

    class Meta:
        model = Pic
        fields = ('title', 'description', 'image', 'userprofile', 'score')
        order_by = (('title',))

    def get_score(self, obj):
        return Rating.objects.filter(picc=obj).aggregate(Avg('score'))['score__avg']
+4
source share
1 answer

get_score class Pic. , .

, score "", class Pic (, ...), .

+3

Source: https://habr.com/ru/post/1568888/


All Articles