I have a very simple APIView
, but I don't know how to setup pagination here.
In this scenario I select an Event
with given pk
, then I get all the NewsItems
assigned to this Event
.
pagination_class = LimitOffsetPagination
works OK when I define queryset at the beginning in ListCreateAPIView
, for ex. queryset = Event.objects.all()
but not with custom 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
Solved:
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
question from:
https://stackoverflow.com/questions/35830779/django-rest-framework-apiview-pagination 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…