tomchristie/django-rest-framework — pull request #982 by mjumbewu (2013-07-12 13:48:20+00:00)
Title: Add Field.many_to_native for more control over iterable serialization

Add many_to_native to fields for more control over iterable object serialization. My particular use-case is that I have a model where each instance corresponds to a Twitter user. I want to retrieve and cache users' avatars, full names, and other information from Twitter on an as-needed basis -- essentially when the corresponding user instance needs to be serialized. However, I don't want to make a separate Twitter API call for each user if I have a number of them (waste of time and API limits). Instead, when I know I'm going to be serializing them in bulk, I want to precache as much as I can at once.

My Serializer would look something like:

class UserSerializer (ModelSerializer):
avatar_url = SerializerMethodField('get_avatar_url')

class Meta:
model = User

...

def get_avatar_url(self, obj):
service = self.get_twitter_service()

# Use the cached info, if available. Otherwise, fetch it.
return service.get_avatar_url(obj)

def many_to_native(self, many_obj):
service = self.get_twitter_service()

# Hit the service once and cache all the users' info.
service.get_users_info(many_obj)
return super(UserSerializer, self).many_to_native(many_obj)

The serializer for this model is used as a field in several other serializers as well.