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?
Thread.objects.filter(board=requested_board)[:5].update(title='whatever')
. This WOULD work if not for the [:5] slicing. A current workaround consists of usingitertools.chain
, but that gives back anitertools
object, which then has to be converted to a list to even be sent as a template context from a view. Works but it's very messy and unreadable.value_list
or similar), and plug them back in to form a new query usingupdate
. A little ugly, but not Django's fault, as explained there (UPDATE... WHERE... LIMIT...
is not OK in SQL).filter(id__in=sliced_queryset)
.