其他分享
首页 > 其他分享> > 创建线程注释模型Django

创建线程注释模型Django

作者:互联网

我有一个存储评论的模型.

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用于父字段.您可以这样使用,并可以实现注释线程.

标签:python,django,django-models
来源: https://codeday.me/bug/20191120/2043202.html