# Generated by Django 5.0.6 on 2024-08-20 03:45

import django.db.models.deletion
from django.db import migrations, models


def update_snapshottag_ids(apps, schema_editor):
    Tag = apps.get_model("core", "Tag")
    SnapshotTag = apps.get_model("core", "SnapshotTag")
    num_total = SnapshotTag.objects.all().count()
    print(f'   Updating {num_total} SnapshotTag.tag_id values in place... (may take an hour or longer for large collections...)')
    for idx, snapshottag in enumerate(SnapshotTag.objects.all().only('old_tag_id').iterator(chunk_size=500)):
        assert snapshottag.old_tag_id
        tag = Tag.objects.get(old_id=snapshottag.old_tag_id)
        snapshottag.tag_id = tag.id
        snapshottag.save(update_fields=["tag_id"])
        assert str(snapshottag.tag_id) == str(tag.id)
        if idx % 100 == 0:
            print(f'Migrated {idx}/{num_total} SnapshotTag objects...')


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0062_alter_snapshottag_old_tag'),
    ]

    operations = [
        migrations.AddField(
            model_name='snapshottag',
            name='tag',
            field=models.ForeignKey(blank=True, db_column='tag_id', null=True, on_delete=django.db.models.deletion.CASCADE, to='core.tag', to_field='id'),
        ),
        migrations.AlterField(
            model_name='snapshottag',
            name='old_tag',
            field=models.ForeignKey(db_column='old_tag_id', on_delete=django.db.models.deletion.CASCADE, related_name='snapshottags_old', to='core.tag'),
        ),
        migrations.RunPython(update_snapshottag_ids, reverse_code=migrations.RunPython.noop),
    ]
