问题描述
我想在保存新记录(而不是更新现有记录)时触发 Django 模型对象的 save() 方法中的特殊操作.
I want to trigger a special action in the save() method of a Django model object when I'm saving a new record (not updating an existing record.)
检查 (self.id != None) 是否必要且足以保证 self 记录是新的且未更新?这可能会忽略任何特殊情况?
Is the check for (self.id != None) necessary and sufficient to guarantee the self record is new and not being updated? Any special cases this might overlook?
推荐答案
更新: 澄清 self._state
不是私有实例变量,而是将其命名为为了避免冲突,检查 self._state.adding
现在是更好的检查方法.
Updated: With the clarification that self._state
is not a private instance variable, but named that way to avoid conflicts, checking self._state.adding
is now the preferable way to check.
self.pk is None:
在新的 Model 对象中返回 True,除非该对象有一个 UUIDField
作为它的 primary_key
.
returns True within a new Model object, unless the object has a UUIDField
as its primary_key
.
您可能需要担心的极端情况是除了 id 之外的字段是否存在唯一性约束(例如,其他字段上的二级唯一索引).在这种情况下,您手头可能仍有新记录,但无法保存.
The corner case you might have to worry about is whether there are uniqueness constraints on fields other than the id (e.g., secondary unique indexes on other fields). In that case, you could still have a new record in hand, but be unable to save it.
这篇关于在 django 模型自定义 save() 方法中,你应该如何识别一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!