Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot update a query once a slice has been taken". Best practices?

Tags:

python

django

Because of the nature of my project, I find myself constantly taking slices out of querysets, like so:

Thread.objects.filter(board=requested_board_id).order_by('-updatedate')[:10]

But this leaves me with the problem of actually DOING stuff with the elements that I have selected, because any kind of .update() or .filter() won't work after slicing.

I know of several ways to get around it, but they are all messy and confusing and seriously degrade the readability of the code, especially when I have to do it so often.

What's the best way to get around this slice-filter limitation?

like image 915
flatterino Avatar asked Feb 04 '16 16:02

flatterino


1 Answers

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)
like image 186
flatterino Avatar answered Sep 30 '22 18:09

flatterino