Django Rest Framework Ordering on a SerializerMethodField

后端 未结 2 451
庸人自扰
庸人自扰 2020-12-14 09:10

I have a Forum Topic model that I want to order on a computed SerializerMethodField, such as vote_count. Here are a very simplified Model, Serializer and ViewSet to show the

相关标签:
2条回答
  • 2020-12-14 09:15

    I will put it here because the described case is not the only one. The idea is to rewrite the list method of your Viewset to order by any of your SerializerMethodField(s) also without moving your logic from the Serializer to the ModelManager (especially when you work with several complex methods and/or related models)

    def list(self, request, *args, **kwargs):
        response = super(YourModelList, self).list(request, args, kwargs)
        ordering = request.query_params.get('ordering')
        response.data['results'] = sorted(response.data['results'], key=operator.itemgetter(ordering.replace('-',''),))
    
        if "-" in ordering:      
            response.data['results'] = sorted(response.data['results'], key=lambda k: (k[ordering.replace('-','')], ), reverse=True)
        else:
            response.data['results'] = sorted(response.data['results'], key=lambda k: (k[ordering], ))
    
        return response
    
    0 讨论(0)
  • 2020-12-14 09:28

    This is not possible using the default OrderingFilter, because the ordering is implemented on the database side. This is for efficiency reasons, as manually sorting the results can be incredibly slow and means breaking from a standard QuerySet. By keeping everything as a QuerySet, you benefit from the built-in filtering provided by Django REST framework (which generally expects a QuerySet) and the built-in pagination (which can be slow without one).

    Now, you have two options in these cases: figure out how to retrieve your value on the database side, or try to minimize the performance hit you are going to have to take. Since the latter option is very implementation-specific, I'm going to skip it for now.

    In this case, you can use the Count function provided by Django to do the count on the database side. This is provided as part of the aggregation API and works like the SQL COUNT function. You can do the equivalent Count call by modifying your queryset on the view to be

    queryset = Topic.objects.annotate(vote_count=Count('topicvote_set'))
    

    Replacing topicvote_set with your related_name for the field (you have one set, right?). This will allow you to order the results based on the number of votes, and even do filtering (if you want to) because it is available within the query itself.

    This would require making a slight change to your serializer, so it pulls from the new vote_count property available on objects.

    class TopicSerializer(serializers.ModelSerializer):
        vote_count = serializers.IntegerField(read_only=True)
    
        class Meta:
            model = Topic
    

    This will override your existing vote_count method, so you may want to rename the variable used when annotating (if you can't replace the old method).


    Also, you can pass a method name as the source of a Django REST framework field and it will automatically call it. So technically your current serializer could just be

    class TopicSerializer(serializers.ModelSerializer):
        vote_count = serializers.IntegerField(read_only=True)
    
        class Meta:
            model = Topic
    

    And it would work exactly like it currently does. Note that read_only is required in this case because a method is not the same as a property, so the value cannot be set.

    0 讨论(0)
提交回复
热议问题