在django模式中定制save()方法,你应该如何识别一个新对象? [英] In a django model custom save() method, how should you identify a new object?
问题描述
是否(self.id!= None)的支票是必要和足够的,以保证自我记录是新的并且不被更新?任何特殊情况可能会忽略?
self.pk is None:
在新的Model对象中返回True,除非对象有一个 UUIDField
作为其 primary_key
。
您可能需要担心的角落是否有唯一性约束在id以外的字段(例如,其他字段上的辅助唯一索引)。在这种情况下,您仍然可以拥有新的记录,但无法保存。
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.)
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.pk is None:
returns True within a new Model object, unless the object has a UUIDField
as its primary_key
.
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()方法,你应该如何识别一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!