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
posted @ 2023-02-22 10:20  vx_guanchaoguo0  阅读(116)  评论(0编辑  收藏  举报