Django - 使用树形结构构建评论系统
几天前,我在玩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()
2 个回答
1
我只会定义一个父级,并给它起个相关的名字。
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()
2
可以看看这个叫做 django-threadedcomments 的项目。它的主要用途是用作博客上的评论,而不是一个功能齐全的论坛。不过,如果这个项目不适合你的需求,你至少可以看看它的源代码,从中学到一些东西。
关于树形结构,我知道有三个适用于Django的ORM的项目:django-mptt(这个项目在第三方Django应用中占有最大的“市场份额”),django-treebeard,还有 easytree(这个是基于treebeard的)。Easytree有一个不错的管理界面,但另外两个项目在它们的问题跟踪器中至少有一些补丁可以添加管理界面(不确定它们是否已经整合了这些补丁)。