I’m trying to create a custom function in a model manager:
class MessageManager(models.Manager):
# Return body from last child message
def get_last_child_body(self):
if self.has_childs:
last_child = self.filter(parent_msg=self.id).order_by('-send_at')[0]
return last_child.body
I want to use this function (“get_last_child_body”) in template
{% message.get_last_child_body %}
to retrieve the body from the last child message inserted in table message.
The Message model:
class Message(models.Model):
sender = models.ForeignKey(User, related_name='sent_messages')
recipient = models.ForeignKey(User, related_name='received_messages')
parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True)
has_childs = models.BooleanField()
subject = models.CharField(max_length=120)
body = models.TextField()
send_at = models.DateTimeField()
read_at = models.DateTimeField(null=True, blank=True)
replied_at = models.DateTimeField(null=True, blank=True)
sender_deleted_at = models.DateTimeField(null=True, blank=True)
recipient_deleted_at = models.DateTimeField(null=True, blank=True)
objects = MessageManager()
def get_last_child(self):
if not self.has_childs:
return None
class Meta:
get_latest_by = 'send_at'
ordering = ['-send_at']
Well, I’m guessing the problem is located in “id” from custom function in manager. I have to pass the parent message id but i don’t know how can i do it.
It does not report any error, it just does not show anything in template.
Any ideas?
Managers should be used for Model specific operators. Here however you are doing an instance specific operation so the
get_last_child_bodyshould be inside yourMessageclass.In comments you mentioned you tried to move it. It should work, something else is probably wrong. You should verify that: