2012-05-13 42 views
0

我試圖創建一個模型管理器的自定義功能,建立與字段的值,在經理的自定義函數:我需要從一個模型

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」 )in template

{% 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,但我不知道我該怎麼做。

它不報告任何錯誤,它只是不顯示任何模板。

任何想法?

+0

你爲什麼認爲這應該在經理?爲什麼不在模型上,就像'get_last_child'? –

+0

爲此,我一直在尋找django文檔和互聯網上的信息,我不知道爲什麼,但我認爲這是最好的方式。 我錯了嗎? –

+0

好吧,我試着把模型上的get_last_child_body放在你對我說的模型上。它不運行。 –

回答

0

經理應該用於特定於模型的操作員。但是,您正在執行特定於實例的操作,因此get_last_child_body應位於您的Message類中。

在您提到的評論中,您嘗試過移動它。它應該工作,其他的可能是錯誤的。您應該驗證:

  1. 消息模板中定義(使用例如如果模板標籤記錄結果)
  2. get_last_child_body被調用(例如使用打印語句)
  3. 繼續調試更深層次仍是沒有結果(打印報表工作,如果它對你來說最簡單)
+0

我一直在檢查所有的代碼,我發現了錯誤。我設置: 'LAST_CHILD = self.filter(parent_msg = self.id).order_by( ' - send_at')[0]' 相反: 'LAST_CHILD = Message.objects.filter(parent_msg =自我。 id).order_by(' - send_at')[0]' 現在,它的工作原理。謝謝你的回答! –