删除时序列化模型对象时的AttributeError

AttributeError when serializing model object on deletion

我在一个 django 项目中工作,希望保留被用户删除的对象以进行数据库同步,因此我决定将它们存储在 json 文件中。为此,我覆盖了模型的 delete() 方法。 我首先从文件中检索以前删除的对象,然后添加正在删除的对象。序列化这个新列表时,我得到一个 AttributeError:

AttributeError: 'DeserializedObject' object has no attribute '_meta'

我做错了什么?

这里是 delete() 代码:

def delete(self, *args, **kwargs):
    force = kwargs.pop("force", None)

    if force is None:
        objects_to_delete = list()
        user_dir_path = os.path.join(STATIC_ROOT, self.user.username)
        if not os.path.exists(user_dir_path):
            os.makedirs(user_dir_path)
        path = os.path.join(user_dir_path, "obj_to_delete.json")
        if os.path.exists(path):
            with open(path, "r") as fp:
                json_str = fp.read()
                if len(json_str) > 0:
                    objects_to_delete = list(serializers.deserialize(
                        "json",
                        json_str,
                        indent=4,
                        use_natural_foreign_keys=True, 
                        fields=('pk', 'user', 'slug')
                        ))

        objects_to_delete.append(self)

        if objects_to_delete:
            with open(path, "w") as fp:
                jsonData = serializers.serialize("json", 
                    objects_to_delete, indent=4, 
                    use_natural_foreign_keys=True, 
                    fields=('pk', 'user', 'slug')
                )
                fp.write(jsonData)

    super(UserOwnedModel,self).delete(*args, **kwargs)

https://docs.djangoproject.com/en/1.11/topics/serialization/#deserializing-data

如文档中所述,序列化程序的反序列化方法不会直接 ​​return 您的对象,而是将其包装在 DeserializeObject 中。例如,您需要调用 deserialized_object.object 来访问您的对象。

您可以试试这个:

objects_to_delete = list(obj.object for obj in serializers.deserialize(
    "json",
    json_str,
    indent=4,
    use_natural_foreign_keys=True, 
    fields=('pk', 'user', 'slug')
    ))