3

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

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

这篇文章描述了想要,但没有发布最终代码(除非我误解了它)。

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

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

我该怎么做?

4

1 回答 1

3
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)  # Call the "real" save() method.

    # Set Issue issueCreatedDateTime to the same as IssueHistory issueCreatedDateTime
    self.fk_issueID.issueCreatedDateTime = self.issuehistoryCreatedDateTime
    # Save the Issue
    self.fk_issueID.save()
于 2013-05-09T13:02:13.877 回答