本文整理汇总了Python中rest_framework.relations.HyperlinkedRelatedField方法的典型用法代码示例。如果您正苦于以下问题:Python relations.HyperlinkedRelatedField方法的具体用法?Python relations.HyperlinkedRelatedField怎么用?Python relations.HyperlinkedRelatedField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.relations
的用法示例。
在下文中一共展示了relations.HyperlinkedRelatedField方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_representation
# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import HyperlinkedRelatedField [as 别名]
def to_representation(self, value):
result = {}
for link in self.hyperlink_data:
label = link['label']
kwargs = copy.copy(link)
del kwargs['label']
field = relations.HyperlinkedRelatedField(read_only=True, **kwargs)
# fake the request into the context so the URL can be constructed
field._context = {'request': self.context.get('request', None)}
result[label] = field.to_representation(value)
return result
示例2: convert_resource
# 需要导入模块: from rest_framework import relations [as 别名]
# 或者: from rest_framework.relations import HyperlinkedRelatedField [as 别名]
def convert_resource(self, resource, view):
serializer_data = view.get_serializer(instance=None)
fields = serializer_data.fields
links = {}
if "links" in resource:
links = resource["links"]
del resource["links"]
for field_name, field in six.iteritems(fields):
if field_name not in links:
continue
related_field = get_related_field(field)
if isinstance(related_field, relations.HyperlinkedRelatedField):
if is_related_many(field):
pks = links[field_name]
model = related_field.queryset.model
resource[field_name] = []
for pk in pks:
obj = model(pk=pk)
try:
url = related_field.to_representation(obj)
except AttributeError:
url = related_field.to_native(obj)
resource[field_name].append(url)
else:
pk = links[field_name]
model = related_field.queryset.model
obj = model(pk=pk)
try:
url = related_field.to_representation(obj)
except AttributeError:
url = related_field.to_native(obj)
resource[field_name] = url
else:
resource[field_name] = links[field_name]
return resource