The objects I'm trying to serialize implements iter (I'm working witn mongoengie and the object I'm talking about is of type Document).
The method to_native (https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L274) of the class BaseSerializer, checks if the passed object is a unique object or a list and for this purpose it uses the line hasattr(obj,'iter).
For my particular case this method don't work because the implementation of iter in my native objects (mongoengine Document).
I rewrote the function in my serializer as:
def to_native(self, obj):
Serialize objects -> primitives.
if obj.class == QuerySet:
return [self.convert_object(item) for item in obj]
This is very specific for mongoengine.
Is there maybe other way to do this in a more general elegant way?
I'm going to classify this as a bug. The current behavior is as intended, but it's not ideal, and we should really declare explicitly when a serializer is expected to iterate or not.
Note on turning off implicit many behavior. Refs #564.
Set many explicitly from mixins. Refs #564.
Fixed in master.
Version 2.2 starts the deprecation of the implicit iteration behavior. At the moment you'll need to explicitly specify many=False to force the behavior to not iterate over __iter__ style objects. By 2.4 the default value will switch from None to False.