gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:15 38 4
gpt4 key购买 nike

我在一个 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

如文档中所述,序列化程序的反序列化方法不会直接返回您的对象,而是将其包装在 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')
))

关于python - 删除时序列化模型对象时的AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47435751/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com