Reputation: 1344
def get_notifications(request):
comments_send = EventUser.objects.filter(receive_id=request.user).order_by('-date')[:5]
comments = EventUser.objects.filter(receive_id=request.user,read=False).order_by('-date')
comments.update(read=True)
return render(request, 'home/notifications.html', locals())
After creating an instance of EventUser, I am updating the object. After that I render the instanced object but it shows updated.
{% for c in comments_send %}
...
{% endfor %}
Why does this happen? How can I avoid it?
Upvotes: 0
Views: 26
Reputation: 1558
This is happening because QuerySets are lazy.
So, although it appears that you are pulling out the comments_send
before updated all comments with comments.update(read=True)
, the actual query being sent to the database may differ.
You can force evaluation of the queryset by converting it to a list:
comments_send = list(EventUser.objects.filter(receive_id=request.user).order_by('-date')[:5])
Upvotes: 1
Reputation: 3841
This is because the query is not executed until it is needed (django queryset is lazy by default) and by that time it has already been updated.
So you need to force the "comments_send" to be evaluated. You can force it to evaluate before by casting it to a list.
comments_send = list(comments_send)
before the
comments.update(read=True)
You can see when QuerySets are evaluated in the Django Documenation
Upvotes: 1