在Django rest API中使用GET方法分页似乎不起作用

rjjhvcjd  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(124)

我一直试图分页的json响应,但徒劳的。以下是我的代码片段。
views.py
这给了我完整的结果。我转换到 Dataframe 的原因是我想做一些数据清理和微操作。

class LogsNewAPI(APIView):
pagination_class=CustomPagination
def get(self,request, *args, **kwargs):
    envid = self.kwargs.get('envid')
    nodeid = self.kwargs.get('nodeid')
    startdatetime = self.request.GET.get('startdatetime')
    enddatetime = self.request.GET.get('enddatetime')

    filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime')
    df = read_frame(filter_list)
    json = df[['generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso')
    return HttpResponse(json, content_type = 'application/json')

我也尝试了如下,并给出了错误:
LogsAPI需要“template_name”属性或返回QuerySet的get_queryset()方法

class LogsAPI(ListView):
pagination_class=CustomPagination
def get_queryset(self):
    startdatetime = self.request.GET.get('startdatetime')
    enddatetime = self.request.GET.get('enddatetime')
    filter_list=Alerts.objects.filter(envId=self.kwargs['envid'], serverId=self.kwargs['nodeid'], generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime')
    df = read_frame(filter_list)
    json = df[[
                  'generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso')
    return HttpResponse(json, content_type = 'application/json')

pagination.py

class CustomPagination(pagination.PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
page_query_param = 'page_number'

urls.py

url(r'^api/v1/servers/(?P<envid>\d+)/(?P<nodeid>\d+)/logs/alerts/logs/$',views.LogsNewAPI.as_view(),name='LogsNewAPI'),

Postman 的要求
http://xxxx:xxxx/API/v1/服务器/1/1/日志/警报/日志/?页面大小= 3页面编号= 2开始日期时间=2023-01-08 10:00:00结束日期时间=2023-01-08 15:00:00
不知道我是否错过了什么。任何建议或重定向将是很大的帮助..谢谢!!

hfyxw5xn

hfyxw5xn1#

添加序列化程序类有助于解决此问题。

class LogsNewAPI(GenericAPIView):
        pagination_class=CustomPagination
        serializer_class = AlertsSerializer
        def get(self,request, *args, **kwargs):
            envid = self.kwargs.get('envid')
            nodeid = self.kwargs.get('nodeid')
            startdatetime = self.request.GET.get('startdatetime')
            enddatetime = self.request.GET.get('enddatetime')
            filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime')
            page = self.paginate_queryset(filter_list)
            serializer = AlertsSerializer(page, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

相关问题