def full_dehydrate(self, obj, for_list=False):
"""Convert the given object into a dictionary.
:param for_list: True when the object is being converted to belong
in a list.
"""
if for_list:
allowed_fields = self._meta.list_fields
exclude_fields = self._meta.list_exclude
else:
allowed_fields = self._meta.fields
exclude_fields = self._meta.exclude
data = {}
for field in self._meta.object_class._meta.fields:
# Convert the field name to unicode as some are stored in bytes.
field_name = str(field.name)
# Skip fields that are not allowed.
if allowed_fields is not None and field_name not in allowed_fields:
continue
if exclude_fields is not None and field_name in exclude_fields:
continue
# Get the value from the field and set it in data. The value
# will pass through the dehydrate method if present.
field_obj = getattr(obj, field_name)
dehydrate_method = getattr(
self, "dehydrate_%s" % field_name, None)
if dehydrate_method is not None:
data[field_name] = dehydrate_method(field_obj)
else:
value = field._get_val_from_obj(obj)
if is_protected_type(value):
data[field_name] = value
elif isinstance(field, ArrayField):
data[field_name] = field.to_python(value)
else:
data[field_name] = field.value_to_string(obj)
# Return the data after the final dehydrate.
return self.dehydrate(obj, data, for_list=for_list)
评论列表
文章目录