10
我有一個非常簡單的APIView
,但我不知道如何在這裏設置分頁。 在這種情況下,我選擇Event
與給定pk
,然後我得到所有NewsItems
分配給此Event
。Django Rest框架 - APIView分頁
pagination_class = LimitOffsetPagination
工作正常,當我在ListCreateAPIView
開始定義查詢集,例如。 queryset = Event.objects.all()
但與定製get
:
class EventNewsItems(APIView):
pagination_class = LimitOffsetPagination
def get(self, request, pk, format=None):
#user = request.user
event = Event.objects.get(pk=pk)
news = event.get_news_items().all()
serializer = NewsItemSerializer(news, many=True, context={'request':request})
response = Response(serializer.data, status=status.HTTP_200_OK)
return response
解決:
def get(self, request, pk, format=None):
#user = request.user
event = Event.objects.get(pk=pk)
news = event.get_news_items().all()
paginator = LimitOffsetPagination()
result_page = paginator.paginate_queryset(news, request)
serializer = NewsItemSerializer(result_page, many=True, context={'request':request})
response = Response(serializer.data, status=status.HTTP_200_OK)
return response
回顧這次討論中,看起來像這個傢伙的解決您的問題https://github.com/tomchristie/django-rest-framework/issues/ 3030 – inlanger
嘿,@ user3128673我想知道你是否發現我的答案有幫助。 –