普拉多VX

人生一路,不问来时,不知归期

0%

django drf 获取最新数据并按升序返回

按drf排序

目前使用drf默认的排序只能是升序,降序。如果获取最近的数据,获取的结果是倒序方式。特记录下改问题的解决方法

需求:我需要获取最近100条数据(指定返回的数据量),并按升序方式排列返回。

参考了self.list的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ListModelMixin:
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())

page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)

serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)

直接在返回数据时做一次列表倒序排列 [::-1],修改代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BlocksDiffView(generics.ListAPIView):
serializer_class = block_s.BlocksDiffSerializer


def get_queryset(self):
queryset = block_m.NetworkStats.objects.order_by('-height')
return queryset

# 获取最近多少条数据,然后再升序排列返回
def get(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())

page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data[::-1])

serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)