Skip to content

Commit

Permalink
Pass request to related serializers
Browse files Browse the repository at this point in the history
Related serializers may need access to the request to properly serialize
a child resource.  For example, reverse() in djangorestframework.reverse
uses request if available to return an absolute URL.  While the parent
resource has access to the request to generate the absolute URL, the
child resource does not.
  • Loading branch information
Sean C. Farley committed Jun 26, 2012
1 parent 9dbaac3 commit 1b49c5e
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions djangorestframework/serializer.py
Expand Up @@ -179,7 +179,8 @@ def serialize_val(self, key, obj, related_info):
stack = self.stack[:]
stack.append(obj)

return related_serializer(depth=depth, stack=stack).serialize(obj)
return related_serializer(depth=depth, stack=stack).serialize(
obj, request=self.request)

def serialize_max_depth(self, obj):
"""
Expand Down Expand Up @@ -253,11 +254,15 @@ def serialize_fallback(self, obj):
"""
return smart_unicode(obj, strings_only=True)

def serialize(self, obj):
def serialize(self, obj, request=None):
"""
Convert any object into a serializable representation.
"""

# Request from related serializer.
if request is not None:
self.request = request

if isinstance(obj, (dict, models.Model)):
# Model instances & dictionaries
return self.serialize_model(obj)
Expand Down

1 comment on commit 1b49c5e

@greylurk
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice. This is a much better solution to the problem I was facing. Thanks.

Please sign in to comment.