合并放置到数据库上的对象

2024-09-26 18:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

试图从数据库中的对象中删除自定义属性时遇到问题

我编写了一个方法来合并数据库中已经存在的对象和新发布的对象。 在那里我传递了object类,它包含一个不可更新、非可选、notempty和非公共属性的列表,如下所示:

non_optional_attributes = [IN]
non_updatable_attributes = {ID, TYPE, IN}

假设我有一个db_对象,如下所示:

#DB_Object
{
   IN:"12345",
   TYPE:"tree",
   ID:"T-12345",
   "customAttribute":"value"
}

我想通过put删除customAttribute,只需在没有属性的情况下发布数据(只需将其省略),即可将发布的数据传递给我的合并函数:

#New_Object
{
   IN:"12345",
   TYPE:"tree",
   ID:"T-12345"
}

以下是从db_对象中实际删除缺少的键的部分:

for r_key in deepcopy(result_obj):
                if r_key in db_obj and key not in new_obj and \
                   r_key not in cls.non_empty_attributes and \
                   r_key not in cls.non_optional_attributes and \
                   r_key not in cls.non_updatable_attributes and \
                   r_key not in cls.non_public_response_keys:

                    del result_obj[key]

这里是理解的全部功能:

@classmethod
    def merge_model_object(cls, db_obj, new_obj):
        # validate new_obj first
        cls(new_obj)

        renamed_attrs = cls.get_renamed_attrs()

        # merge: use non_updatable or missing keys from db_obj
        result_obj = deepcopy(db_obj)
        for key, value in new_obj.items():
            if key not in cls.non_updatable_attributes:  # only update if allowed

                # revert values to ids if they have been resolved to objects before
                if key in cls.resolved_attributes or key in renamed_attrs:
                    reverted_attribute = cls.revert_resolved_attribute(value)
                    if reverted_attribute is not None:
                        result_obj[renamed_attrs.get(key, key)] = reverted_attribute

                else:
                    result_obj[key] = value

            elif key in db_obj and db_obj[key] != new_obj[key]:
                if key not in cls.resolved_attributes:
                    raise exceptions.ChangingNonUpdatableAttribute(key)

            for r_key in deepcopy(result_obj):
                if r_key in db_obj and key not in new_obj and \
                   r_key not in cls.non_empty_attributes and \
                   r_key not in cls.non_optional_attributes and \
                   r_key not in cls.non_updatable_attributes and \
                   r_key not in cls.non_public_response_keys:

                    del result_obj[key]

        return result_obj

当我将断点放在那里并检查自定义键的情况时,它只是跳过了删除。我已经再次检查了,钥匙在非限制列表中。所以我不明白为什么它没有被删除。 有人有主意吗

此外,这里还有一个屏幕截图,显示了限制列表在运行时获得的值:

enter image description here


Tags: and对象keyinobjnewdbif

热门问题