Skip to content

Instantly share code, notes, and snippets.

@atroche
Created October 24, 2011 10:59
Show Gist options
  • Save atroche/1308771 to your computer and use it in GitHub Desktop.
Save atroche/1308771 to your computer and use it in GitHub Desktop.
def save(self, message):
"""Append new comment to the message, increment comment_count."""
user = current_user._get_current_object()
# Set the comment's pk to -1 so we can find it in the comment list
# (We can't guarantee it will be last when we go to access it)
comment = Comment(body=clean_html_input(self.body.data),
author=user, pk=-1)
message_qs = Message.objects(id=message.id)
message_qs.update(push__comments=comment)
message_qs.update(inc__cache__comments_count=1)
message_qs.update(set__updated_at=datetime.datetime.now())
comments_length = len(message.comments)
if comments_length:
# Go backwards until we find the first comment with a positive pk
# (because the most recent comment might still have a pk of -1,
# after just being pushed to msg.comments.)
prev_comment_index = comments_length - 1
for i in reversed(xrange(comments_length)):
if message.comments[i].pk:
prev_comment_pk = message.comments[i].pk
break
else:
prev_comment_index = 0
prev_comment_pk = 1
updated_message = message_qs.first()
no_pk_comments = []
for new_comment_index in xrange(len(updated_message.comments)):
if updated_message.comments[new_comment_index].pk == -1:
no_pk_comments.append(new_comment_index)
for no_pk_comment_index in no_pk_comments:
distance = no_pk_comment_index - prev_comment_index
new_comment_pk = prev_comment_pk + distance
kwargs = {"set__comments__%d__pk" % no_pk_comment_index: new_comment_pk}
message_qs.update(**kwargs)
# Add this message to the user following list.
updated_message.add_to_following_list(user)
# Increment user comment_count
user.cache.comment_count += 1
user.save()
return new_comment_pk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment