我正在开发一个django项目,并希望保持用户删除对象以进行数据库同步,因此我决定将它们存储在json文件中。为此,我重写了模型的delete()方法。 我首先从文件中检索以前删除的对象,然后添加要删除的对象。序列化这个新列表时,我得到一个AttributeError:
AttributeError:' DeserializedObject'对象没有属性' _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)
答案 0 :(得分:1)
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')
))