보고있는 동안 필드 값 목록을 변경하고 있지만 변경되지 않은 값을 컨텍스트로 전달하려고합니다. 여기의 경우는 알림을 볼 때 상태를보기로 변경해야하는 기본 알림 시스템입니다.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)'를 평가하고 평가 한 결과를 얻은 후에 QS'len (user_unread)'를 평가했습니다. – Rohan
아, 미안, 못 봤어. –