Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove count, next, previous from response in Django REST framework

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.

like image 401
Christoffer Karlsson Avatar asked Aug 23 '15 19:08

Christoffer Karlsson


2 Answers

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.

like image 83
Alasdair Avatar answered Oct 06 '22 03:10

Alasdair


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.

like image 27
Paul Tuckett Avatar answered Oct 06 '22 04:10

Paul Tuckett