当前位置: 首页>>代码示例>>Python>>正文


Python relations.RelatedField方法代码示例

本文整理汇总了Python中rest_framework.relations.RelatedField方法的典型用法代码示例。如果您正苦于以下问题:Python relations.RelatedField方法的具体用法?Python relations.RelatedField怎么用?Python relations.RelatedField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rest_framework.relations的用法示例。


在下文中一共展示了relations.RelatedField方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: build_json_resource_obj

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def build_json_resource_obj(cls, fields, resource, resource_instance, resource_name,
                                force_type_resolution=False):
        """
        Builds the resource object (type, id, attributes) and extracts relationships.
        """
        # Determine type from the instance if the underlying model is polymorphic
        if force_type_resolution:
            resource_name = utils.get_resource_type_from_instance(resource_instance)
        resource_data = [
            ('type', resource_name),
            ('id', encoding.force_str(resource_instance.pk) if resource_instance else None),
            ('attributes', cls.extract_attributes(fields, resource)),
        ]
        relationships = cls.extract_relationships(fields, resource, resource_instance)
        if relationships:
            resource_data.append(('relationships', relationships))
        # Add 'self' link if field is present and valid
        if api_settings.URL_FIELD_NAME in resource and \
                isinstance(fields[api_settings.URL_FIELD_NAME], relations.RelatedField):
            resource_data.append(('links', {'self': resource[api_settings.URL_FIELD_NAME]}))
        return OrderedDict(resource_data) 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:23,代码来源:renderers.py

示例2: to_native

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def to_native(self, obj):
        res = super(ExtendedHyperlinkedModelSerializer, self).to_native(obj)
        if obj:
            res['id'] = obj.serializable_value('pk')
            for field_name, field in self.fields.items():
                if isinstance(field , HyperlinkedRelatedMethod):
                    serializable_value = getattr(obj, field_name)#obj.serializable_value(field_name)()
                    if callable(serializable_value):
                        serializable_value = serializable_value()
                    res[field_name] = {'url': res[field_name]}
                    res[field_name]["id"] = serializable_value.pk if serializable_value else None
                    res[field_name]["descr"] = str(serializable_value) if serializable_value else None
                    res[field_name]["type"] = str(serializable_value.__class__.__name__).lower() if serializable_value else None
                elif isinstance(field , RelatedField) and hasattr(field, 'attname'):
                    serializable_value = obj.serializable_value(field_name)
                    res[field_name] = {'url': res[field_name]}
                    if isinstance(serializable_value, int):
                        res[field_name]["id"] = obj.serializable_value(field_name)
                        res[field_name]["descr"] = str(getattr(obj, field_name))
                    elif serializable_value == None:
                        res[field_name]["id"] = None
                        res[field_name]["descr"] = None
                #else:
                #  print field_name, field.__class__
        return res 
开发者ID:peragro,项目名称:django-project,代码行数:27,代码来源:serializers.py

示例3: get_choices

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def get_choices(self, cutoff=None):
        """
        Get choices for a field.

        The caller of this method is BrowsableAPIRenderer (indirectly).

        Method is direct copy of ``RelatedField.get_choices``, with one
        modified line (noted below). Line is modified so ``OrderedDict``
        receives hashable keys. The impementation in parent class
        returns result of ``self.to_representaton``, which is not
        hashable in case of this field (``self.to_representaton``
        returns a ``ReturnDict`` object).
        """
        queryset = self.get_queryset()
        if queryset is None:
            # Ensure that field.choices returns something sensible
            # even when accessed with a read-only field.
            return {}

        if cutoff is not None:
            queryset = queryset[:cutoff]

        return OrderedDict(
            [
                (
                    # This line below is modifed.
                    item.pk,
                    self.display_value(item),
                )
                for item in queryset
            ]
        ) 
开发者ID:genialis,项目名称:resolwe,代码行数:34,代码来源:fields.py

示例4: get_links

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def get_links(self, obj=None, lookup_field='pk'):
        request = self.context.get('request', None)
        view = self.context.get('view', None)
        return_data = OrderedDict()

        kwargs = {lookup_field: getattr(obj, lookup_field) if obj else view.kwargs[lookup_field]}

        self_kwargs = kwargs.copy()
        self_kwargs.update({
            'related_field': self.field_name if self.field_name else self.parent.field_name
        })
        self_link = self.get_url('self', self.self_link_view_name, self_kwargs, request)

        # Assuming RelatedField will be declared in two ways:
        # 1. url(r'^authors/(?P<pk>[^/.]+)/(?P<related_field>\w+)/$',
        #         AuthorViewSet.as_view({'get': 'retrieve_related'}))
        # 2. url(r'^authors/(?P<author_pk>[^/.]+)/bio/$',
        #         AuthorBioViewSet.as_view({'get': 'retrieve'}))
        # So, if related_link_url_kwarg == 'pk' it will add 'related_field' parameter to reverse()
        if self.related_link_url_kwarg == 'pk':
            related_kwargs = self_kwargs
        else:
            related_kwargs = {self.related_link_url_kwarg: kwargs[self.related_link_lookup_field]}

        related_link = self.get_url('related', self.related_link_view_name, related_kwargs, request)

        if self_link:
            return_data.update({'self': self_link})
        if related_link:
            return_data.update({'related': related_link})
        return return_data 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:33,代码来源:relations.py

示例5: extract_attributes

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def extract_attributes(cls, fields, resource):
        """
        Builds the `attributes` object of the JSON API resource object.
        """
        data = OrderedDict()
        render_nested_as_attribute = json_api_settings.SERIALIZE_NESTED_SERIALIZERS_AS_ATTRIBUTE
        for field_name, field in iter(fields.items()):
            # ID is always provided in the root of JSON API so remove it from attributes
            if field_name == 'id':
                continue
            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue
            # Skip fields with relations
            if isinstance(
                    field, (relations.RelatedField, relations.ManyRelatedField)
            ):
                continue

            if isinstance(field, BaseSerializer) and not render_nested_as_attribute:
                continue

            # Skip read_only attribute fields when `resource` is an empty
            # serializer. Prevents the "Raw Data" form of the browsable API
            # from rendering `"foo": null` for read only fields
            try:
                resource[field_name]
            except KeyError:
                if fields[field_name].read_only:
                    continue

            data.update({
                field_name: resource.get(field_name)
            })

        return utils.format_field_names(data) 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:38,代码来源:renderers.py

示例6: _readable_id_fields

# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import RelatedField [as 别名]
def _readable_id_fields(self):
        fields = self._readable_fields
        return {
            field for field in fields
            if (
                isinstance(
                    field,
                    (DynamicRelationField, RelatedField)
                )
                and not isinstance(
                    self.request_fields.get(field.field_name), dict
                )
            )
        } 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:16,代码来源:serializers.py


注:本文中的rest_framework.relations.RelatedField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。