2

我有一个简单的聊天应用程序。

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)

每次创建一个 NewMessage 对象时,我想用刚刚创建的 NewMessage 对象的日期时间更新 Thread 模型中的 last_message_time 。我该怎么做呢?

4

1 回答 1

4

最简单的方法可能是post_save使用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)

您还可以saveNewMessage.

于 2013-11-06T20:37:02.780 回答