[Answered ]-How do update last message date in Django model

1👍

If it is an option to not have it at the database, you can just calculate this at the time when you need it. So for that you can use a model property:

class UserPosts(models.Model):
    postTitle = models.CharField(max_length=100, verbose_name="Title")
    postContent = RichTextField(null=True, verbose_name="Content")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Date of upload")
    
    @property
    def last_message(self):
        last_message = self.usermessages_set.order_by('-created_at').first()
        if last_message:
            return last_message.created_at
        return self.created_at

So if a post doesn’t have a message yet, it will get it’s own created_at field. You can then use this like a property:

post = UserPosts.objects.first()
print(post.last_message)

Also consider using cached_property if you plan to use this field in a view multiple times.

Leave a comment