python - Creating threaded comments model Django -
i have model 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, want add in ability reply comment (threaded comments)i.e.
1 comment 1 2 reply comment 1 3 reply comment 2 4 reply comment 2 5 reply comment 4 6 reply comment 1 7 reply comment 1 i hoping achieved adding self refereeing related field comments model i.e.
child = models.foreignkey(comment) but i'm unsure work , how nested replies each comment using above method.
my question is, there correct way of doing this, , how?
yeah of course can that. can find recursive elements , should use django-mptt model. nested comments of specific comments 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 of 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) 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 parent field. can use such , can achieved comment threads.
Comments
Post a Comment