简体   繁体   English

创建线程注释模型Django

[英]Creating threaded comments model Django

I have a model which stores comments . 我有一个存储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')

However, I now want to add in the ability to reply to a comment (threaded comments)ie 但是,我现在想要添加回复评论(线程评论)的能力,即

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

I was hoping this could be achieved by adding a self refereeing related field into the comments model ie 我希望通过在评论模型中添加自我裁判相关字段来实现这一点,即

child = models.ForeignKey(Comment)

But I'm unsure this would work and how I would get the nested replies for each comment using the above method. 但我不确定这会起作用,以及如何使用上述方法获得每个评论的嵌套回复。

My question is, is there a correct way of doing this, and how? 我的问题是,有没有正确的方法来做到这一点,以及如何?

yeah of course you can do that. 是的,你当然可以做到这一点。 You can find the recursive elements and for that you should use django-mptt model. 你可以找到递归元素,为此你应该使用django-mptt模型。 To get nested comments of specific comments you can use below functions. 要获取特定注释的嵌套注释,可以使用以下函数。

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:])

In Above code, sub_comment is for parent field. 在上面的代码中, sub_comment用于父字段。 You can use such like that and can be achieved comment threads. 你可以使用这样的,并可以实现评论线程。

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

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