Editing a Django Comment

99封情书 提交于 2019-12-11 20:16:05

问题


I'm attempting to edit an existing comment (i.e. replace old comment with a new one). My comments app is django.contrib.comments.

new_comment = form.cleaned_data['comment']

#all of the comments for this particular review
comments = Comment.objects.for_model(Review).filter(object_pk=review_id)

print comments[0].comment
#'old comment'

comments[0].comment = new_comment

print comments[0].comment
#'old comment' is still printed

Why is the comment not being updated with the new comment ?

Thank you.

Edit: Calling comments[0].save() and then print comments[0].comment, still prints 'old comment'


回答1:


This isn't to do with comments specifically. It's simply that querysets are re-evaluated every time you slice. So the first comments[0], which you change, is not the same as the second one - the second one is fetched again from the database. This would work:

comments = Comment.objects.for_model(Review).filter(object_pk=review_id)
comment = comments[0]
comment.comment = new_comment

Now you can save or print comment as necessary.




回答2:


You need to save the value

comments = comments[0]    
comments.comment = new_comment
comments.save()


来源:https://stackoverflow.com/questions/12564023/editing-a-django-comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!