Reputation: 1610
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?
Upvotes: 14
Views: 2757
Reputation: 10931
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()
Upvotes: 7
Reputation: 12895
DateTime fields with auto_now are automatically updated upon calling save()
, so you do not need to update them manually. Django will do this work for you.
Upvotes: 1
Reputation: 15286
You would also need to then save the message. Then it that should work.
Upvotes: 12