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


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:


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


Leave a comment