Created
November 6, 2012 20:37
-
-
Save minism/4027356 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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