繁体   English   中英

创建线程注释模型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用于父字段。 你可以使用这样的,并可以实现评论线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM