From a51bca32fd26ae954228b9026b18ebeea81ad8e2 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 26 Jan 2013 20:54:41 +0000 Subject: [PATCH] Fix issues with custom pagination serializers --- rest_framework/pagination.py | 20 ++++++++++++-------- rest_framework/serializers.py | 7 ++++++- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 5755a235d..92d41e0e2 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -34,6 +34,17 @@ class PreviousPageField(serializers.Field): return replace_query_param(url, self.page_field, page) +class DefaultObjectSerializer(serializers.Field): + """ + If no object serializer is specified, then this serializer will be applied + as the default. + """ + + def __init__(self, source=None, context=None): + # Note: Swallow context kwarg - only required for eg. ModelSerializer. + super(DefaultObjectSerializer, self).__init__(source=source) + + class PaginationSerializerOptions(serializers.SerializerOptions): """ An object that stores the options that may be provided to a @@ -44,7 +55,7 @@ class PaginationSerializerOptions(serializers.SerializerOptions): def __init__(self, meta): super(PaginationSerializerOptions, self).__init__(meta) self.object_serializer_class = getattr(meta, 'object_serializer_class', - serializers.Field) + DefaultObjectSerializer) class BasePaginationSerializer(serializers.Serializer): @@ -70,13 +81,6 @@ class BasePaginationSerializer(serializers.Serializer): self.fields[results_field] = object_serializer(source='object_list', **context_kwarg) - def to_native(self, obj): - """ - Prevent default behaviour of iterating over elements, and serializing - each in turn. - """ - return self.convert_object(obj) - class PaginationSerializer(BasePaginationSerializer): """ diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c38768094..6ecc7b458 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -2,6 +2,7 @@ import copy import datetime import types from decimal import Decimal +from django.core.paginator import Page from django.db import models from django.forms import widgets from django.utils.datastructures import SortedDict @@ -273,7 +274,11 @@ class BaseSerializer(Field): """ Serialize objects -> primitives. """ - if hasattr(obj, '__iter__'): + # Note: At the moment we have an ugly hack to determine if we should + # walk over iterables. At some point, serializers will require an + # explicit `many=True` in order to iterate over a set, and this hack + # will disappear. + if hasattr(obj, '__iter__') and not isinstance(obj, Page): return [self.convert_object(item) for item in obj] return self.convert_object(obj)