When I'm doing a GET on my API, it always includes the following in the result:
{
"count": 2013,
"next": "http://127.0.0.1:8000/api/items/?page=2",
"previous": null,
"results": [ {...} ... {...} ]
}
How can I remove the count, next, and previous fields and just return what's in results? I still want the results paginated, though.
I found something here: Django REST Framework: Directly display on results list in GenericView, but it didn't work.
Override the get_paginated_response
method of your pagination class.
from rest_framework.pagination import PageNumberPagination
class PageNumberPaginationDataOnly(PageNumberPagination):
# Set any other options you want here like page_size
def get_paginated_response(self, data):
return Response(data)
Then in your settings.py, set DEFAULT_PAGINATION_CLASS
to your new pagination class.
DEFAULT_PAGINATION_CLASS = 'path.to.PageNumberPaginationDataOnly'
This approach is used in the example in the pagination docs.
Another solution to this problem, would be to redefine the get_pagination_response
in each viewset within your views.py. This makes it so you can alter each viewset dynamically. Also, make sure you import Response from rest_framework.response.
from rest_framework.response import Response
from rest_framework import viewsets
from .models import CustomModel
from .serializers import CustomSerialzer
class CustomViewSet(viewsets.ModelViewSet):
queryset = CustomModel.objects.all()
serializer_class = CustomSerializer
def get_paginated_response(self, data):
return Response(data)
I also found this little gem: paginator = None
Just simply stick it underneath the serializer_class on your viewset and it will take your pagination out and make it so you can return all your list items on one page. However, might be risky if you have too many records. So be cautious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With