我正在尝试在模型管理器中创建自定义函数:
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
我想在模板中使用这个函数(“get_last_child_body”)
{% message.get_last_child_body %}
从插入到表消息中的最后一条子消息中检索正文。
消息模型:
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']
好吧,我猜问题出在管理器中自定义函数的“id”中。我必须传递父消息 ID,但我不知道该怎么做。
它不报告任何错误,只是在模板中不显示任何内容。
有任何想法吗?