我在db中为此字段保存新值后,尝试显示db模型字段(RelatedModel.new_reply
)的旧值。这应该起作用的方式是new_reply
字段将回复(通过将其设置为1)标记为收件人(rto
)未读。收件人查看邮件后,new_reply
将重置为0.模板my_view.html会向收件人显示一个标记,如果他们有一个尚未点击查看的新回复。收件人第一次查看回复时,标记new_reply
将被重置,后续视图不会被标记为新文件。
问题是除了存储在db中的值之外,行response.save()
似乎也会更改new_reply
中d
的值。因此,my_view.html永远不会看到new_reply==1
,只会看到new_reply==0
。这对我来说似乎很奇怪,因为d
一旦分配就应该独立于db。
为什么会发生这种情况以及如何解决这个问题?
class ParentModel (models.Model):
msg = models.TextField()
author = models.ForeignKey(User)
class RelatedModel (models.Model):
msg = models.ForeignKey(ParentModel)
reply = models.TextField()
rto = models.ForeignKey(User, related_name='rto')
new_reply = models.IntegerField(null=True, blank=True)
def view_msg(request, msg_id):
m = get_object_or_404(ParentModel, pk=id)
r = m.RelatedModel_set.all()
d = add_csrf(request, m=m, r=r) # d.r.new_reply==1 should be rendered
# Once the view data is ready for rendering, clear the new_reply
# bit. If we do it earlier, we will not be able to mark replies as new.
if request.user.is_authenticated():
for response in r:
# Clear bit if current user is viewing reply addressed to them
if (request.user == RelatedModel.rto):
if response.new_reply == 1: # Is it a new reply?
response.new_reply = 0 # Reset the new_activity bits
response.save()
return render_to_response('my_view.html',
{'db_data': d},
context_instance = RequestContext(request),
)