42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
from django.db import migrations
|
|
|
|
|
|
def collapse_ids(apps, schema_editor):
|
|
"""Collapse each owner/owner_group's InventoryItem ids from the sparse global range they
|
|
had before this migration down to a continuous 1..N range, in original creation order
|
|
(internal_id order), including soft-deleted rows since they still occupy a slot in that
|
|
scope's history. Then seed OwnerItemSequence so future allocation continues right after."""
|
|
InventoryItem = apps.get_model('toolshed', 'InventoryItem')
|
|
OwnerItemSequence = apps.get_model('toolshed', 'OwnerItemSequence')
|
|
|
|
scope = None
|
|
next_id = 0
|
|
counts = {}
|
|
for item in InventoryItem.objects.order_by('owner_id', 'owner_group_id', 'internal_id'):
|
|
key = (item.owner_id, item.owner_group_id)
|
|
if key != scope:
|
|
scope = key
|
|
next_id = 0
|
|
next_id += 1
|
|
item.id = next_id
|
|
item.save(update_fields=['id'])
|
|
counts[key] = next_id
|
|
|
|
for (owner_id, owner_group_id), count in counts.items():
|
|
OwnerItemSequence.objects.update_or_create(
|
|
owner_id=owner_id, owner_group_id=owner_group_id, defaults={'last_id': count})
|
|
|
|
|
|
def noop_reverse(apps, schema_editor):
|
|
pass
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('toolshed', '0015_inventoryitem_id'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(collapse_ids, noop_reverse),
|
|
]
|