简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM