+
+ def __init__(self, parent=None, **kwargs):
+ """Constructor override to set left/right correctly on a new comment.
+ """
+ super(Comment, self).__init__(**kwargs)
+
+ # Keep the comment count updated
+ self.discussion.count += 1
+
+ if parent:
+ # Parent comment given. Add this comment just before the parent's
+ # right side...
+ self.left = parent.right
+ self.right = parent.right + 1
+
+ # ...then adjust all rightward comments accordingly
+ Comment.query.filter(Comment.discussion == self.discussion) \
+ .filter(Comment.right > parent.right) \
+ .update({ Comment.left: Comment.left + 2,
+ Comment.right: Comment.right + 2 })
+
+ # And, finally, update the parent's right endpoint
+ parent.right += 2
+
+ else:
+ query = session.query(func.max(Comment.right)) \
+ .filter(Comment.discussion == self.discussion)
+ (max_right,) = query.one()
+
+ if not max_right:
+ # No comments yet. Use 1 and 2
+ self.left = 1
+ self.right = 2
+ else:
+ self.left = max_right + 1
+ self.right = max_right + 2