Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top