[Fixed]-"Cannot update a query once a slice has been taken". Best practices?

30👍

So far, based on the comments, I have found this solution by Daniel Roseman to be the least “ugly”:

sliced_queryset = Somemodel.objects.filter(field='fieldvalue')[:5]

And then use id__in= to reference the sliced queryset objects’ IDs:

Somemodel.objects.filter(id__in=sliced_queryset).update(field_to_update='whatever')

It works well, I’ve just tried it.

I wish Django had a more ‘direct’ way of doing this, but it’s still pretty straightforward. If anyone has a better way, please post it and I will mark your answer as correct.


As a bit of extra advice, if you’re using this to increment a field, like a ‘views’ field, you can self reference it cleanly like this:

from django.db.models import F

Somemodel.objects.filter(id__in=sliced_queryset).update(views=F('views')+1)

Leave a comment