创建线程评论模型 Django

Creating threaded comments model Django

我有一个存储 comments 的模型。

class Comment(TimeStampedModel):
    content = models.TextField(max_length=255)
    likes = models.IntegerField(default=0)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

但是,我现在想添加回复评论(线程评论)的功能,即

1 Comment 1
   2 Reply to Comment 1
      3 Reply Comment 2
      4 Reply Comment 2
        5 Reply Comment 4
   6 Reply to Comment 1
   7 Reply to Comment 1

我希望这可以通过在评论模型中添加一个自我推荐相关字段来实现,即

child = models.ForeignKey(Comment)

但我不确定这是否可行,也不确定如何使用上述方法获得每个评论的嵌套回复。

我的问题是,是否有正确的方法,如何做?

是的,你当然可以这样做。您可以找到递归元素,为此您应该使用 django-mptt 模型。 要获取特定评论的嵌套评论,您可以使用以下函数。

class Comment(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='sub_comment')
    # Other fields


    def get_all_children(self, include_self=False):
        """
        Gets all of the comment thread.
        """
        children_list = self._recurse_for_children(self)
        if include_self:
            ix = 0
        else:
            ix = 1
        flat_list = self._flatten(children_list[ix:])
        return flat_list

    def _recurse_for_children(self, node):
        children = []
        children.append(node)
        for child in node.sub_comment.enabled():
            if child != self
                children_list = self._recurse_for_children(child)
                children.append(children_list)
        return children

    def _flatten(self, L):
        if type(L) != type([]): return [L]
        if L == []: return L
        return self._flatten(L[0]) + self._flatten(L[1:])

在上面的代码中,sub_comment 用于父字段。可以这样用,也可以实现评论帖。