James
James

Reputation: 865

updating an auto_now DateTimeField in a related model

I would like to update a related models timestamp when saving a record. Here are my 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

This post describes want but the final code wasn't posted (unless I am misunderstanding it).

To further clarify, this is the desired order of events:

  1. Save a new issue history record
  2. save() is overridden, uses the custom
  3. IssueHistory record is saved
  4. Related Issue record's "issueCreatedDateTime" field is updated to the current datetime

How should i do this?

Upvotes: 4

Views: 2075

Answers (1)

rockingskier
rockingskier

Reputation: 9346

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

Upvotes: 3

Related Questions