1

I am using the Django REST Frameworks Paginator to paginate the JSON responses read from a database.

My current serializers.py file looks like this:

class CountrySerializer(serializers.Serializer):
    country_geoname_id = serializers.CharField(required=True)
    country_code = serializers.CharField(source="iso", max_length=2L, required=True)
    country_name = serializers.CharField(max_length=64L, required=True)

    paginate_by_param = "offset"

    def transform_iso(self, obj, value):
        return "country_code"

class PaginatedCountrySerializer(pagination.PaginationSerializer):
    paginate_by_param = "offset"
    class Meta:
        object_serializer_class = CountrySerializer
        paginate_by_param = "offset"

The request/response currently looks like this:

GET /v4/api/v1/countries/?limit=1&offset=1
{
    "count": 250, 
    "next": "http://dev.fanmode.com/v4/api/v1/countries/?limit=2&page=2&offset=1", 
    "previous": null, 
    "results": [
        {
            "country_geoname_id": 3041565, 
            "country_code": "AD", 
            "country_name": "Andorra"
        }, 
        ...
    ]
}

Could someone help me by telling me:

  • How do I modify the names of these? for example I want to change where it says 'page=2' in the next field to 'limit=2'. I have tried 'PAGINATE_BY_PARAM': 'limit' in the settings.py file but this didn't work.
  • How do I remove fields all together. I want to remove 'count' and 'previous' from the response.

Appreciate any help I can get. Thanks.

LondonAppDev
  • 8,501
  • 8
  • 60
  • 87

1 Answers1

1

You can change the page_field in NextPageField class inside pagination.py file to permanently change the name from page to limit.

For the second part you can write your own custom PaginationSerializer:

from rest_framework.pagination import BasePaginationSerializer, NextPageField
class MyPaginationSerializer(BasePaginationSerializer):

    next = NextPageField(source='*')

Now only the next and results field will be returned.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Thanks a lot. How do I link the MyPaginationSerializer to the serializer I am using? How does it know to use this serializer? I tried adding `pagination_serializer_class = MyPaginationSerializer` to the PaginatedCountrySerializer meta class but it didn't work. Thanks again. – LondonAppDev Nov 12 '13 at 14:38
  • @MarkWinterbottom Have a look at these exampled: http://django-rest-framework.org/api-guide/pagination.html#paginating-querysets – Ashwini Chaudhary Nov 12 '13 at 15:46
  • PaginationSerializer is deprecated in django 1.8 – bryanph Aug 12 '15 at 12:06