Last active
August 29, 2015 14:25
-
-
Save PCreations/39296bfe6db5925be663 to your computer and use it in GitHub Desktop.
HyperlinkedNestedRelatedField
This file contains 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 HyperlinkedNestedRelatedField(HyperlinkedRelatedField): | |
def __init__(self, view_name, additional_reverse_kwargs, **kwargs): | |
super(HyperlinkedNestedRelatedField, self).__init__( | |
view_name, | |
read_only=True, | |
**kwargs | |
) | |
self.additional_reverse_kwargs = additional_reverse_kwargs | |
def get_url(self, obj, view_name, request, format): | |
if obj.pk is None: | |
return None | |
kwargs = {self.lookup_url_kwarg: getattr(obj, self.lookup_field)} | |
for kwarg_name, field_name in self.additional_reverse_kwargs.items(): | |
try: | |
parent_object = _resolve_object_attribute(obj, field_name) | |
except AttributeError: | |
#PKOnlyObject here. Since it's a mock object we can't directly getattr() of obj. | |
if isinstance(self.root.instance, QuerySet): | |
parent_object = getattr(self.root.instance.get(pk=obj.pk), field_name) | |
else: | |
parent_object = getattr(self.root.instance, field_name) | |
kwargs[kwarg_name] = parent_object.pk | |
url = self.reverse( | |
view_name, | |
kwargs=kwargs, | |
request=request, | |
format=format, | |
) | |
return url | |
def _resolve_object_attribute(object_, attribute_name): | |
attribute = object_ | |
for attribute_name_part in attribute_name.split('.'): | |
attribute = getattr(attribute, attribute_name_part) | |
return attribute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment