Django Rest Framework Ordering on a SerializerMethodField

后端 未结 2 452
庸人自扰
庸人自扰 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
    

提交回复
热议问题