gpt4 book ai didi

django - 更新相关模型中的 auto_now DateTimeField

转载 作者:行者123 更新时间:2023-12-01 22:55:15 26 4
gpt4 key购买 nike

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

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”字段已更新为当前日期时间

我应该怎么做?

最佳答案

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()

关于django - 更新相关模型中的 auto_now DateTimeField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16462101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com