0040_archiveresult_snapshot.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. # Generated by Django 5.0.6 on 2024-08-18 06:46
  2. import django.db.models.deletion
  3. from django.db import migrations, models
  4. def update_archiveresult_snapshot_ids(apps, schema_editor):
  5. ArchiveResult = apps.get_model("core", "ArchiveResult")
  6. Snapshot = apps.get_model("core", "Snapshot")
  7. num_total = ArchiveResult.objects.all().count()
  8. print(f' Updating {num_total} ArchiveResult.snapshot_id values in place... (may take an hour or longer for large collections...)')
  9. for idx, result in enumerate(ArchiveResult.objects.all().only('snapshot_old_id').iterator(chunk_size=5000)):
  10. assert result.snapshot_old_id
  11. snapshot = Snapshot.objects.only('id').get(old_id=result.snapshot_old_id)
  12. result.snapshot_id = snapshot.id
  13. result.save(update_fields=["snapshot_id"])
  14. assert str(result.snapshot_id) == str(snapshot.id)
  15. if idx % 5000 == 0:
  16. print(f'Migrated {idx}/{num_total} ArchiveResult objects...')
  17. class Migration(migrations.Migration):
  18. dependencies = [
  19. ('core', '0039_rename_snapshot_archiveresult_snapshot_old'),
  20. ]
  21. operations = [
  22. migrations.AddField(
  23. model_name='archiveresult',
  24. name='snapshot',
  25. field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='archiveresults', to='core.snapshot', to_field='id'),
  26. ),
  27. migrations.RunPython(update_archiveresult_snapshot_ids, reverse_code=migrations.RunPython.noop),
  28. ]