deadlock
deadlock

Reputation: 7310

Django: How to update the field of another model during object creation

I have a simple chat app.

class Thread(models.Model):
     participants = models.ManyToManyField(User)
     last_message_time = models.DateTimeField(null=True, blank=True)

class NewMessage(models.Model):
     message = models.CharField(max_length=500)
     sender = models.ForeignKey(User)
     thread = models.ForeignKey(Thread, related_name = 'thread_to_message')
     datetime = models.DateTimeField(auto_now_add=True)

Every time a a NewMessage object is created, I would like to update the last_message_time in the Thread model with the datetime from the NewMessage object that was just created. How can I go about doing this?

Upvotes: 2

Views: 1907

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

The simplest way is probably with a post_save signal handler for NewMessage.

from django.db.models.signals import post_save

def update_thread(sender, **kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    raw = kwargs['raw']
    if created and not raw:
        instance.thread.last_message_time = instance.datetime
        instance.thread.save()

post_save.connect(update_thread, sender=NewMessage)

You could also use a custom save method on NewMessage.

Upvotes: 4

Related Questions