我正在更改查看時字段值的列表,但我想將未更改的值傳遞給上下文。這裏的情況是一個原始通知系統,在查看通知後,它應該將其狀態更改爲查看。Django:在上下文中傳遞模型後更改模型
views.py
class Notification(TemplateView):
template_name='myapp/notification.html'
def get_context_data(self, **kwargs):
user = self.request.user
user_unread = user.notification_set.filter(viewed=False)
user_read = user.notification_set.filter(viewed=True)
context = super(Notification, self).get_context_data(**kwargs)
context.update({'user_unread': user_unread, 'user_read': user_read})
for msg in user_unread:
msg.viewed = True
msg.save()
return context
然而與此代碼的問題是,我得到重複值在讀和未讀名單,即使我已經更新了上下文之後保存到模型中的新值傳遞給模板。
模板:
Unread:
<ul>
{% for msg in user_unread %}
<li> {{ msg }} </li>
{% endfor %}
</ul>
Already read:
<ul>
{% for msg in user_read %}
<li> {{ msg }} </li>
{% endfor %}
</ul>
在一個旁註,我是新來的CBVS,如果有,如果我認爲上面的代碼可以改善我喜歡一些指點。
不,這是行不通的,原因完全一樣:查詢集在更新完成後才進行評估,因此這些消息總是顯示爲已讀。 –
@DanielRoseman,已經提到並評估了QS'len(user_unread)',以便在得到它之後進行評估。 – Rohan
啊,對不起,沒有看到。 –