在django模式中定制save()方法,你应该如何识别一个新对象? [英] In a django model custom save() method, how should you identify a new object?

查看:181
本文介绍了在django模式中定制save()方法,你应该如何识别一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我保存新的记录(不更新现有记录)时,我想在Django模型对象的save()方法中触发一个特殊的操作。



是否(se​​lf.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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆