Fix issues with custom pagination serializers

This commit is contained in:
Tom Christie 2013-01-26 20:54:41 +00:00
parent b41f258ee5
commit a51bca32fd
2 changed files with 18 additions and 9 deletions

View File

@ -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):
"""

View File

@ -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)