"Unable to update request after slice has been done." Best practics?

Due to the nature of my project, I am constantly taking fragments from requests, for example:

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

But this leaves me with the problem of actually doing things with the elements that I selected, because any kind of .update () or .filter () will not work after slicing.

I know several ways around this, but they are all messy and confusing and seriously impair code readability, especially when I have to do this so often.

What is the best way to get around the limitation of this slice filter?

+4
source share
1 answer

, , "":

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

id__in= :

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

, .

, Django "" , . - , , .


, , , "views", :

from django.db.models import F

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

Source: https://habr.com/ru/post/1627326/


All Articles