Cannot update a query once a slice has been taken

Posted under » Django on 26 June 2022

When you have a queryset like

initial = Guid.objects.filter(taken=0).order_by('uid') [:1]

You will get the error, 'Cannot update a query once a slice has been taken'. It is because

Taking a slice is equivalent to a LIMIT statement in SQL
Issuing an update turns your query into an UPDATE statement

What you are trying to do would be equivalent to UPDATE ... WHERE ... LIMIT 1

What you need to do is to take away the limit statement. You can do this by using the .get statement which will take only one uid.

initial = Guid.objects.filter(taken=0).order_by('uid') [:1].get()
took = initial.uid
take = Guid.objects.filter(uid=took)

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS IOT