40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
from django.db import migrations
|
|
|
|
|
|
def collapse_ids(apps, schema_editor):
|
|
"""Collapse each owner's StorageLocation 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). Then
|
|
seed OwnerStorageLocationSequence so future allocation continues right after."""
|
|
StorageLocation = apps.get_model('toolshed', 'StorageLocation')
|
|
OwnerStorageLocationSequence = apps.get_model('toolshed', 'OwnerStorageLocationSequence')
|
|
|
|
scope = None
|
|
next_id = 0
|
|
counts = {}
|
|
for location in StorageLocation.objects.order_by('owner_id', 'internal_id'):
|
|
key = location.owner_id
|
|
if key != scope:
|
|
scope = key
|
|
next_id = 0
|
|
next_id += 1
|
|
location.id = next_id
|
|
location.save(update_fields=['id'])
|
|
counts[key] = next_id
|
|
|
|
for owner_id, count in counts.items():
|
|
OwnerStorageLocationSequence.objects.update_or_create(owner_id=owner_id, defaults={'last_id': count})
|
|
|
|
|
|
def noop_reverse(apps, schema_editor):
|
|
pass
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('toolshed', '0020_storagelocation_id'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(collapse_ids, noop_reverse),
|
|
]
|