简体   繁体   中英

Creating threaded comments model Django

I have a model which stores 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. 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. You can use such like that and can be achieved comment threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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