问题
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