django 全局分页在DRF项目上不起作用

kiz8lqtg  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(214)

我在DRF上编写了一个API,它根据特定条件返回一个数据列表,但数据非常大,全局分页不适用于它。结果,速度变慢,因此,数据不能在单个页面上正确显示。
我在www.example.com文件中添加了以下代码settings.py:

REST_FRAMEWORK = {
        "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
        "PAGE_SIZE": 10
    }

这是我的API:

class TeacherViewSet(ModelViewSet):
    queryset = Teacher.objects.all()
    serializer_class = serializers.TeacherSerializer
    authentication_classes = [TokenAuthentication]

    def list(self, request, *args, **kwargs):
        response = []
        for teacher in queryset:
            name = Student.objects.filter(teacher=teacher).values("name")
            res = {"name": name}
            response.append(res)

        return Response(response)

我做错什么了吗?

xqkwcwgp

xqkwcwgp1#

因为您要覆写list方法,所以停用分页功能。预设的list方法如下所示:

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)

注意paginate_querysetget_paginated_response方法执行分页。所以如果你需要覆盖list,你应该包括这些方法:

def list(self, request, *args, **kwargs):
    response = []
    queryset = self.filter_queryset(self.get_queryset())
    queryset = self.paginate_queryset(queryset)
    for teacher in queryset:
        name = Student.objects.filter(teacher=teacher).values("name")
        res = {"name": name}
        response.append(res)
    return self.get_paginated_response(response)

与原始问题无关,但请注意,在循环内执行DB查询被认为是不好的做法,可能会影响视图的性能。请考虑使用prefetch_related,而不是在for循环内为每个教师获取学生。

相关问题