[Answered ]-Updating an auto_now DateTimeField in a parent model in Django Framework

1👍

Yes, that’s correct! Calling self.message.save() ensures that the changes to the associated message’s updated field are persisted to the database. This way, both the attachment and the associated message will have their updated fields updated when an attachment is saved.

0👍

auto_now=True will ignore anything you set to it, and will use the current timestamp.

Indeed, take a look at the .pre_save(…) of a DateTimeField [GitHub]:

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = timezone.now()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super().pre_save(model_instance, add)

So if self.auto_now or self.auto_now_add is used, it will omit the value, and set timezone.now() as value instead, regardless what you "throw" at the instance.

You thus can update the updated of the message, you can use:

def save(self):
    super().save()
    self.message.save()

this will however not guarantee that both .updated fields will be the same. This is because between the two queries, time will pass, and thus the timestamp can be different.

Leave a comment