Skip to content

Instantly share code, notes, and snippets.

@minism
Created November 6, 2012 20:37
Show Gist options
  • Save minism/4027356 to your computer and use it in GitHub Desktop.
Save minism/4027356 to your computer and use it in GitHub Desktop.
class NestedLazyModelField(serializers.ModelSerializer):
"""
Use this class for defining a nested relationship based on a funciton
instead of an attribute.
For example, 'get_profile' method of user
"""
def field_to_native(self, obj, field_name):
obj = getattr(obj, self.source or field_name)
# FIX: Resolve obj if its callable
if fields.is_simple_callable(obj):
obj = obj()
# If the object has an "all" method, assume it's a relationship
if fields.is_simple_callable(getattr(obj, 'all', None)):
return [self.to_native(item) for item in obj.all()]
return self.to_native(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment