I'm trying to call a method in my Conversation model to get the latest message in my template. Here's my model.py:
from django.db import models
from django.contrib.auth.models import User
class Conversation(models.Model):
participants = models.ManyToManyField(User)
def get_last_message(self):
lastmessage = Message.objects.filter(conversation=self).order_by('id')[0]
return lastmessage
class Message(models.Model):
sender = models.ForeignKey(User, on_delete= models.CASCADE, related_name="sender")
recipient = models.ForeignKey(User, on_delete= models.CASCADE, related_name="recipient")
text = models.TextField(null=False, blank=False)
timestamp = models.DateTimeField(auto_now_add=True)
conversation = models.ForeignKey(Conversation, blank=False, null=False, on_delete=models.CASCADE)
def __str__(self):
return self.text
And here is my template:
{% for conversation in conversations %}
<p>{{ conversation.get_latest_message.text }}</p>
I don't see any errors but there isn't any output. I can display the conversation.participants fine, but the call to the get_latest_message
method doesn't do anything.
What am I missing?
Thanks!