我有以下基于类的视图,它们按预期工作,并根据需要使用参数http://127.0.0.1:8000/api/collection/fromdetroit?page=1
>> ?page=2
等对页面进行分页
class ListReleasesCollectionView(APIView):
def get(self, request, format=None, *args, **kwargs):
try:
releases = ReleasesAll.objects.raw('SELECT releases.*, \'\' as num FROM releases_all releases INNER JOIN release_artists ra ON ra.release_id=releases.id LEFT JOIN genre_artists ON genre_artists.artist=ra.artists LEFT JOIN genre_labels ON genre_labels.label=releases.label_no_country WHERE genre_artists.genre=%s OR genre_labels.genre=%s GROUP by releases.id ORDER BY releases.date DESC',(kwargs['collection'],kwargs['collection']))
paginator = PageNumberPagination()
result_page = paginator.paginate_queryset(releases, request)
serializer = ReleasesSerializer(result_page, many=True, context={'request': request})
response = Response({'results':{'image_url':'', 'page_header':'','releases': serializer.data}}, status=status.HTTP_200_OK)
return response
except ReleasesAll.DoesNotExist:
return Response(
data = {
"message": "{} does not exist".format(kwargs["collection"])
},
status=status.HTTP_404_NOT_FOUND
)
但是,它运行速度非常慢,因为它必须先下载所有结果,然后再分页。这是Django工具栏的结果。
我一次只能下载60个结果,因为上面返回了成千上万个结果。
settings.py
中的分页设置
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10
}
答案 0 :(得分:0)
添加分页类别。创建pagination_class.py。
from rest_framework.pagination import PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
page_size_query_param = 'limit'
将此添加到settings.py。
REST_FRAMEWORK = {
...
'DEFAULT_PAGINATION_CLASS': 'app_name.pagination_class.StandardResultsSetPagination',
...
}