如何使用django框架返回分页?
我正在尝试使用LimitOffsetPagination类。
我要去哪里错了?
谢谢你们
class Sellers(APIView):
pagination_class = LimitOffsetPagination
def get(self, request):
transactions = Transactions.objects.all()
page = self.paginate_queryset(transactions, request)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(transactions, many=True)
return Response(serializer.data)
page = self.paginate_queryset(transactions, request)
AttributeError: 'Sellers' object has no attribute 'paginate_queryset'
答案 0 :(得分:1)
我认为APIView不支持pagination
。您需要使用GenericAPIView
:
class Sellers(GenericAPIView):
pagination_class = LimitOffsetPagination
def get(self, request):
transactions = Transactions.objects.all()
page = self.paginate_queryset(transactions)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = YourSerializer(transactions, many=True)
return Response(serializer.data)
或更简单地使用django rest框架为您处理一切的ListAPIView
:
class Sellers(ListAPIView):
serializer_class = YourSerializer # you need to define a serializer and put it here
queryset = Transactions.objects.all()
def dispatch(self, request, *args, **kwargs):
if request.GET.get('offset', None) and self.request.GET.get('limit', None):
self._paginator = LimitOffsetPagination
else:
self._paginator = PageNumberPagination
return super(Sellers, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return Transactions.objects.filter(user=request.session['user_id'])
# You don't need to override the `.get()` method
答案 1 :(得分:0)
我们可以利用通用ListAPIView
的优势。您可以使用内置功能来加快开发速度,如下所示。
class Sellers(ListAPIView):
pagination_class = LimitOffsetPagination
queryset = Transactions.objects.all()
参考: https://www.django-rest-framework.org/api-guide/generic-views/#listapiview
答案 2 :(得分:0)
使用winSCP->Server and protocol information dialogue, which lists MD5 and SHA-256 keys nice and explicitly. I have tried both key strings, with and without prefixes like
而不是self.pagination_class
编辑Ruddura的第二个答案,因为它会引发一些奇怪的错误。
修改后的答案:
self._paginator
然后在settings.py中添加:
class Sellers(ListAPIView):
serializer_class = YourSerializer # you need to define a serializer and put it here
queryset = Transactions.objects.all()
def dispatch(self, request, *args, **kwargs):
if request.GET.get('offset', None) and self.request.GET.get('limit', None):
self.pagination_class = LimitOffsetPagination
else:
self.pagination_class = PageNumberPagination
return super(Sellers, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return Transactions.objects.filter(user=request.session['user_id'])
# ...
return self.get_paginated_response(self.paginate_queryset(serializer.data))