本文整理匯總了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