从django休息中获取最大价值

时间:2017-03-19 10:04:21

标签: python django django-rest-framework max

我正在使用django rest框架,而不是获取对象的完整列表,我只想获得一个特定的值,例如max(date)。这是我正在使用的代码:

My Serializer

class MoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mood
        fields = ('date', 'rating')

    def create(self, validated_data):
        return Mood.objects.create(**validated_data)

我的观点

class MoodList(generics.ListCreateAPIView):
    queryset = Mood.objects.all()
    serializer_class = MoodSerializer


class MoodDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Mood.objects.all()
    serializer_class = MoodSerializer

我的网址

  url(r'^mood/$', views.MoodList.as_view()),
  url(r'^mood/(?P<pk>[0-9]+)/$', views.MoodDetail.as_view()),

因此,如果在“max_mood”上激活GET,我想从数据库中获取最新的Mood条目。

3 个答案:

答案 0 :(得分:0)

而不是Mood.objects.all(),为什么不按Mood排序some_criteria个对象并获取第一个( max 一个)。像这样:

mood = Mood.objects.order_by('-some_criteria').first()

还有另一种方法,但它需要额外的查询:

from django.db.models import Max

maximum = Mood.objects.aggregate(m=Max('some_criteria')).get('m')
max_mood = Mood.objects.get(some_criteria=maximum)

答案 1 :(得分:0)

查看

class MaxMoodView(generics.RetrieveAPIView):
    queryset = Mood.objects.all()
    serializer_class = MoodSerializer

    def retrieve(self, request, *args, **kwargs):
        mood=self.get_queryset().order_by('-date').first()
        return Response(self.get_serializer(instance=mood))

网址

  url(r'^mood/max_mood/$', views.MaxMoodView.as_view()),

答案 2 :(得分:0)

好吧,我在评论的帮助下得到了它:

观点:

class MaxMoodView(generics.ListCreateAPIView):
    queryset = Mood.objects.all()
    serializer_class = MoodSerializer

    def get(self, request, format=None):
        mood=self.get_queryset().order_by('-date').first()
        serializer = MoodSerializer(mood)
        return Response(serializer.data)

网址:

url(r'^mood/max_mood/$', views.MaxMoodView.as_view()),