gpt4 book ai didi

python - 使用未保存的相关对象保存对象

转载 作者:行者123 更新时间:2023-11-28 22:35:34 29 4
gpt4 key购买 nike

django 没有提供自动保存未保存的相关对象的功能吗?

来自docs :

Changed in Django 1.8.4:

Previously, saving an object with unsaved related objects did not raise an error and could result in silent data loss. In 1.8-1.8.3, unsaved model instances couldn’t be assigned to related fields, but this restriction was removed to allow easier usage of in-memory models.

我能理解为什么会有

ValueError: save() prohibited to prevent data loss due to unsaved related object

而不是默认保存该对象(我的猜测是显式优于隐式),但我什至无法找到上述功能请求。

最佳答案

来自ticket that lead to the change

I prefer failing early and loudly, by raising an exception when an unsaved object is assigned to a related field.

I could listen to an argument for trying to re-fetch the pk from the cached related instance in save(), but that feels like action-at-a-distance: the actual problem usually happened earlier.

Automatically saving related objects is too magic; I'm sure it would be considered unexpected and undesirable in some circumstances.

我的解释是,Django 的开发者不希望人们养成自动保存东西的习惯,因为这只会导致在不同的时间点出现问题。每个对象的显式保存可确保开发人员充分了解保存的内容,并减少对一行代码中断功能的意外更改。

关于python - 使用未保存的相关对象保存对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095209/

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