1

I have a "index" field stores a consequent range of integers, for safety i set it unique.

now I want to increase this field by one, to keep unique I update the value in a descending order:

MyModel.objects.all().order_by('-index').update(index=F('index')+1)

what surprises me is that on some machine an IntegrityError gets raised and complains for duplicated index value.

is there anything i missed? could I only save records one by one?

thanks in advance!

UPDATE:

I think the root problem is that there is no ORDER BY in an SQL UPDATE command (see UPDATE with ORDER BY, and also SQL Server: UPDATE a table by using ORDER BY)

Obviously django simply translates my statement into a SQL UPDATE with ORDER_BY, which leads to an undefined behavior and creates different result per machine.

Community
  • 1
  • 1
Sam
  • 133
  • 10

1 Answers1

1

You are ordering the queryset ascending. You can make it descending by adding the '-' to the field name in the order by:

MyModel.objects.all().order_by('-index').update(index=F('index')+1)

Django docs for order_by

Fran Muñoz
  • 154
  • 3