Last active
February 4, 2016 14:28
-
-
Save Guest007/9e82e7d5edc6fcc8ca79 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
from rest_framework.relations import HyperlinkedRelatedField, PKOnlyObject | |
class HyperlinkedNestedRelatedField(HyperlinkedRelatedField): | |
def __init__(self, view_name, parent_fields_by_kwargs, **kwargs): | |
super(HyperlinkedNestedRelatedField, self).__init__( | |
view_name, | |
read_only=True, | |
source='*', | |
**kwargs | |
) | |
self._parent_fields_by_kwargs = parent_fields_by_kwargs | |
def get_url(self, obj, view_name, request, format): | |
if obj.pk is None: | |
return None | |
kwargs = {} | |
for k, v in self.additional_reverse_kwargs.iteritems(): | |
args = v.split('.') | |
source = obj | |
for arg in args: | |
if not isinstance(obj, PKOnlyObject): | |
source = getattr(source, arg) | |
else: | |
try: | |
obj = self.get_queryset().first().__class__.objects.get(pk=source.pk) | |
except AttributeError: | |
obj = self.root.instance.__class__.objects.get(pk=source.pk) | |
source = getattr(obj, arg) | |
kwargs[k] = source | |
kwargs.update({self.lookup_url_kwarg: getattr(obj, self.lookup_field)}) | |
return self.reverse(view_name, kwargs=kwargs, request=request, format=format) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment