更新相关模型中的auto_now DateTimeField

时间:2013-05-09 12:45:12

标签: django django-models

我想在保存记录时更新相关模型的时间戳。这是我的模特:

class Issue(models.Model):
    issueTitle = models.CharField()
    issueDescription = models.TextField()
    issueCreatedDateTime = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.issueTitle

class IssueHistory(models.Model):
    fk_issueID = models.ForeignKey(Issue)
    issuehistoryDetail = models.TextField()
    issuehistoryCreatedBy = models.ForeignKey(User)
    issuehistoryCreatedDateTime = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.fk_issueID

    def save(self): #1.1
        # Call parent's `save` function
        # Record is saved like it would be normally, without the override
        super(IssueHistory, self).save() #1.2   

        #This is where i believe i should be updating the "issueCreatedDateTime" to the same datetime

这个post描述了想要但最后的代码没有发布(除非我误解了)。

为了进一步澄清,这是所需的事件顺序:

  1. 保存新问题历史记录
  2. save()被覆盖,使用自定义
  3. 已保存IssueHistory记录
  4. 相关问题记录的“issueCreatedDateTime”字段已更新为当前日期时间
  5. 我该怎么做?

1 个答案:

答案 0 :(得分:1)

 def save(self):
    super(IssueHistory, self).save() #1.2   

    # Set Issue issueCreatedDateTime to the same as IssueHistory issueCreatedDateTime
    self.fk_issueID.issueCreatedDateTime = self.issuehistoryCreatedDateTime
    # Save the Issue
    self.fk_issueID.save()