簡體   English   中英

Django-使用樹構建注釋系統

[英]Django - Using trees to build a comment system

幾天前,當我決定嘗試建立一個簡單的論壇(類似於我經常光顧的一個論壇,但現在已關閉)時,我正與Django混為一談,以嘗試了解東西的工作原理。 想法是每個評論都可以是任意數目評論的父級,例如:

 comment <--top
   comment <-- comment "A"
   comment <-- comment "B"
   comment <-- comment "C"
     comment <--C-1, reply to comment "C"
       comment <-- C-1-1, reply to comment "C-1"
         comment 
           comment 
             comment
         comment <-- C-1-1-1 reply to C-1-1
         comment 
         comment
           comment
             comment
     comment
     comment
       comment
         comment
           comment
             comment
             comment
             comment

這里的想法是,對評論的回復將在其下方填充一個級別,並且每個評論(除了第一個評論之外)都有一個父級。 問題是,盡管我有了實現樹遍歷的想法,但是我所讀過的書/文章都沒有考慮Django(或者說是MVC模式),所以我的問題是我該怎么做在Django中實現此系統? (這是我可以參考的模型代碼:-/)

class Comment(models.Model): 
 Parent = models.OneToOneField('self', null=True)
 Children = models.ForeignKey('self', null=True)

 Author = models.ForeignKey(User)
        Author_IP = models.IPAddressField()
 Created_On = models.DateTimeField(auto_now_add=True)
 Modified_On = models.DateTimeField(auto_now=True)
 Body = models.TextField()

看看django-threadedcomments 目的是更適合用作博客評論,而不是功能齊全的論壇,但如果它不適合您的情況,則您至少可以查看源代碼並從中學習一些內容。

就基於樹的結構而言,我知道針對Django ORM的三個項目: django-mptt (這是第三方django應用AFAIK的最大“市場份額”), django-treebeardeasytree (基於胡須)。 Easytree帶有一個不錯的管理界面,但是其他兩個項目的問題跟蹤器中至少有補丁程序可以添加管理界面(不確定是否已經集成了這些補丁程序)。

我只會定義父對象並給它一個相關的名稱

class Comment(models.Model):
  parent=models.ForeignKey('self', related_name="children", null=True, blank=True)
  #other fields 

那你就可以得到它的孩子

comment=Comment.objects.get(id=1)
children=comment.children.all()

for child in children:
  morechildren=child.children.all()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM