Issue
I have two models where users create a post and comment on that post. When users comment this post I want updating last_message date on UserPost model. If there are no comments yet I want the default last_message date to be set to the date the post was created.
Models:
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")
last_message = ?????????????????
def __str__(self):
return self.postTitle
class UserMessages(models.Model):
postMessages = RichTextField(null=True, verbose_name="Message")
post = models.ForeignKey(
UserPosts, on_delete=models.CASCADE, verbose_name="Linked Post", null=True)
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Date of upload")
EDİT
MY VİEWS:
def forums(request,forumname):
forum = Category.objects.get(categoryName=forumname)
post2 = UserPosts.objects.all().filter(category=forum.id).order_by("-
usermessages").filter(category=forum.id)
context = {
'posts': post2,
}
return render(request, "_forums.html",context)
MY TEMPLATE:
{% for post in posts %}
<div class="mb-2 text-muted">
{{post.last_message | naturaltime}}
</div>
{% endfor %}
I couldn’t find anything relevant to this topic in the Django docs, Google, and other sources.
Solution
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.
Answered By – Brian Destura
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0