Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Order on custom field from serializer?

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']
like image 423
user1835351 Avatar asked Oct 19 '22 20:10

user1835351


1 Answers

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.

like image 148
ferrangb Avatar answered Oct 30 '22 20:10

ferrangb