Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an auto_now DateTimeField in a parent model in Django

I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:

def save(self):
    super(Attachment, self).save()
    self.message.updated = self.updated

Will this work, and if you can explain it to me, why? If not, how would I accomplish this?

like image 247
Ellen Teapot Avatar asked Aug 21 '08 19:08

Ellen Teapot


2 Answers

You would also need to then save the message. Then it that should work.

like image 65
John Avatar answered Nov 15 '22 16:11

John


Proper version to work is: (attention to last line self.message.save())

class Message(models.Model):
    updated = models.DateTimeField(auto_now = True)
    ...

class Attachment(models.Model):
    updated = models.DateTimeField(auto_now = True)
    message = models.ForeignKey(Message)

    def save(self):
        super(Attachment, self).save()
        self.message.save()
like image 7
Serjik Avatar answered Nov 15 '22 18:11

Serjik