开发者

How do you detect a new instance of the model in Django's model.save() [duplicate]

This question already has answers here: 开发者_如何学C In a django model custom save() method, how should you identify a new object? (14 answers) Closed 2 years ago.

While overriding the specific model's save() method, Is it possible determine whether it's a new record or an update?


If self.pk is None it is a new record.

def save(self):
    if self.pk is None:
        self.created = datetime.today()
    self.modified = datetime.today()
    super(ProjectCost, self).save()

This topic has been discussed also here


The preferred solution in modern Django is to check self._state.adding

Unfortunately this is not currently documented, but there is an open task to do so https://code.djangoproject.com/ticket/31502

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜