【发布时间】:2015-07-14 12:52:23
【问题描述】:
我有一个论坛主题模型,我想在计算的 SerializerMethodField 上排序,例如 vote_count。下面是一个非常简化的 Model、Serializer 和 ViewSet 来显示问题:
# models.py
class Topic(models.Model):
"""
An individual discussion post in the forum
"""
title = models.CharField(max_length=60)
def vote_count(self):
"""
count the votes for the object
"""
return TopicVote.objects.filter(topic=self).count()
# serializers.py
class TopicSerializer(serializers.ModelSerializer):
vote_count = serializers.SerializerMethodField()
def get_vote_count(self, obj):
return obj.vote_count()
class Meta:
model = Topic
# views.py
class TopicViewSet(TopicMixin, viewsets.ModelViewSet):
queryset = Topic.objects.all()
serializer_class = TopicSerializer
以下是有效的:
- OrderingFilter 默认开启,我可以成功订购
/topics?ordering=title - vote_count 函数完美运行
我正在尝试通过 TopicSerializer 上的 MethodField 进行排序,vote_count 类似于 /topics?ordering=-vote_count,但似乎不受支持。有什么方法可以按那个字段排序吗?
我的简化 JSON 响应如下所示:
{
"id": 1,
"title": "first post",
"voteCount": 1
},
{
"id": 2,
"title": "second post",
"voteCount": 8
},
{
"id": 3,
"title": "third post",
"voteCount": 4
}
我正在使用 Ember 来使用我的 API,而解析器正在将其转换为 camelCase。我也尝试过 ordering=voteCount,但这不起作用(也不应该)
【问题讨论】:
标签: django django-rest-framework