Cannot update a query once a slice has been taken
As the error states, you cannot call update()
on a QuerySet if you took out a slice.
The reason:
- Taking a slice is equivalent to a
LIMIT
statement in SQL. - Issuing an update turns your query into an
UPDATE
statement.
What you are trying to do would be equivalent to
UPDATE ... WHERE ... LIMIT 5
which is not possible, at least not with standard SQL.
The documentation suggests that something like the following might be possible - I'm not sure if doing the limiting in an inner QuerySet
bypasses the check around calling update()
after slicing:
inner_q = UserLog.objects.filter(user=user,
action='message',
timestamp__lt=now).values('pk')[0:5]
UserLog.objects.filter(pk__in=inner_q).update(read=True)
Failing that, you could use the in
field lookup like so:
ids = UserLog.objects.filter(user=user,
action='message',
timestamp__lt=now).values_list('pk', flat=True)[0:5]
UserLog.objects.filter(pk__in=list(ids)).update(read=True)
Since Django 2.2 you can use bulk updates :
queryset = UserLog.objects.filter(user=user).filter(action='message').filter(timestamp__lt=now)
bulk = []
for userlog in queryset[0:5]:
userlog.read = True
bulk.append(userlog)
UserLog.objects.bulk_update(bulk,['read'])
I was getting the same error when attempting to limit the number of records returned by a queryset.
I found that if we're using one of Django's class-based generic views such as the ArchiveIndexView, we can use the paginate_by =
attribute to limit the number of records.
For example (in views.py):
from django.views.generic import ArchiveIndexView
from .models import Entry
class HomeListView(ArchiveIndexView):
""" Blog Homepage """
model = Entry
date_field = 'pub_date'
template_name = 'appname/home.html'
queryset = Entry.objects.filter(
is_active=True).order_by('-pub_date', 'title')
paginate_by = 30