Python rest_framework.serializers.HyperlinkedRelatedField() Examples

The following are 5 code examples of rest_framework.serializers.HyperlinkedRelatedField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .
Example #1
Source File: object_lookup_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_object(self):
        """
        Incase the lookup is on an object that has been hyperlinked
        then update the queryset filter appropriately
        """
        if self.kwargs.get(self.lookup_field, None) is None:
            raise ParseError(
                'Expected URL keyword argument `%s`.' % self.lookup_field
            )
        queryset = self.filter_queryset(self.get_queryset())

        filter_kwargs = {}
        serializer = self.get_serializer()
        lookup_field = self.lookup_field

        if self.lookup_field in serializer.get_fields():
            k = serializer.get_fields()[self.lookup_field]
            if isinstance(k, serializers.HyperlinkedRelatedField):
                lookup_field = '%s__%s' % (self.lookup_field, k.lookup_field)

        filter_kwargs[lookup_field] = self.kwargs[self.lookup_field]

        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #2
Source File: multi_lookup_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_object(self):
        queryset = self.filter_queryset(self.get_queryset())
        filter_kwargs = {}
        serializer = self.get_serializer()
        lookup_fields = getattr(self, 'lookup_fields', [])

        for field in lookup_fields:
            lookup_field = field

            if lookup_field in serializer.get_fields():
                k = serializer.get_fields()[lookup_field]

                if isinstance(k, serializers.HyperlinkedRelatedField):
                    if k.source:
                        lookup_field = k.source
                    lookup_field = '%s__%s' % (lookup_field, k.lookup_field)

            if self.kwargs.get(field, None) is None:
                raise ParseError(
                    'Expected URL keyword argument `%s`.' % field
                )
            filter_kwargs[lookup_field] = self.kwargs[field]

        obj = get_object_or_404(queryset,  **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj 
Example #3
Source File: object_lookup_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pre_save(self, obj):
        """
        Set any attributes on the object that are implicit in the request.
        """
        # pk and/or slug attributes are implicit in the URL.
        lookup = self.kwargs.get(self.lookup_field, None)
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        slug = self.kwargs.get(self.slug_url_kwarg, None)
        slug_field = slug and self.slug_field or None

        if lookup:
            serializer = self.get_serializer()
            k = serializer.get_fields()[self.lookup_field]
            queryset = self.get_queryset()
            queryset = self.filter_queryset(queryset)
            if isinstance(k, serializers.HyperlinkedRelatedField):
                filter = {}
                lookup_field = '%s__%s' % (self.lookup_field, k.lookup_field)
                filter[lookup_field] = lookup
                k_obj = get_object_or_404(queryset, **filter)
                lookup = getattr(k_obj, self.lookup_field)
            setattr(obj, self.lookup_field, lookup)

        if pk:
            setattr(obj, 'pk', pk)

        if slug:
            setattr(obj, slug_field, slug)

        # Ensure we clean the attributes so that we don't eg return integer
        # pk using a string representation, as provided by the url conf kwarg.
        if hasattr(obj, 'full_clean'):
            exclude = mixins._get_validation_exclusions(
                obj, pk, slug_field, self.lookup_field)
            obj.full_clean(exclude) 
Example #4
Source File: renderers.py    From ChRIS_ultron_backEnd with MIT License 5 votes vote down vote up
def _get_related_fields(self, fields, id_field):
        return [k for (k, v) in fields
                if k != id_field
                and (isinstance(v, HyperlinkedRelatedField)
                or isinstance(v, HyperlinkedIdentityField)   
                or isinstance(v, ItemLinkField)
                or (isinstance(v, ManyRelatedField)
                    and isinstance(v.child_relation, HyperlinkedRelatedField)))] 
Example #5
Source File: generic_hyperlinked_related.py    From kpi with GNU Affero General Public License v3.0 4 votes vote down vote up
def to_internal_value(self, data):
        """ The vast majority of this method has been copied and pasted from
        HyperlinkedRelatedField.to_internal_value(). Modifications exist
        to allow any type of object. """
        _ = self.context.get('request', None)
        try:
            http_prefix = data.startswith(('http:', 'https:'))
        except AttributeError:
            self.fail('incorrect_type', data_type=type(data).__name__)

        # The script prefix must be removed even if the URL is relative.
        # TODO: Figure out why DRF only strips absolute URLs, or file bug
        if True or http_prefix:
            # If needed convert absolute URLs to relative path
            data = urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = '/' + data[len(prefix):]

        try:
            match = resolve(data)
        except Resolver404:
            self.fail('no_match')

        # ## Begin modifications ###
        # We're a generic relation; we don't discriminate
        """
        try:
            expected_viewname = request.versioning_scheme.get_versioned_viewname(
                self.view_name, request
            )
        except AttributeError:
            expected_viewname = self.view_name

        if match.view_name != expected_viewname:
            self.fail('incorrect_match')
        """

        # Dynamically modify the queryset
        self.queryset = match.func.cls.queryset
        # ## End modifications ###

        try:
            return self.get_object(match.view_name, match.args, match.kwargs)
        except (ObjectDoesNotExist, TypeError, ValueError):
            self.fail('does_not_exist')