python 嵌套对象转为dict
as_dict(self, keys=None, exclude_keys=None):
"""
将ORM对象序列化为字典
:param keys:
:return:
"""
if not keys:
keys = self.output_fields
keys += ['add_datetime', 'update_datetime', 'uuid']
keys = set(keys)
object_dict = dict()
for key in keys:
if exclude_keys and key in exclude_keys:
continue
value = last_value = getattr(self, key)
if isinstance(value, raw_models.Model):
if isinstance(value, self.__class__):
last_value = value.__unicode__()
else:
last_value = value.as_dict()
if last_value is None:
last_value = ''
object_dict[key] = last_value
key_field = self.__class__._meta.get_field(key)
if key_field.choices: # 如果是下拉列表字段
object_dict[key + '_map'] = dict(key_field.choices)
return object_dict
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17143412.html