5

I'm trying to use Django Rest to return a json representation of a model based on a ordering from a custom field that is not attached to the model, but is attached to the serializer. I know how to do this with model specific fields, but how do you use django rest to return an ordering when the field is only within the serializer class? I want to return a list of Pics ordered by 'score'. Thanks!

------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']

1 Answer 1

3

You could move the logic of the method get_score to the manager of the class Pic. In this answer there is an example of how to do it.

Once you have it in the manager, the score field would become "magically" available for every object of the class Pic everywhere (serializer, views...) and you'll be able to use it for ordering.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.