# Generated by Django 4.1.7 on 2023-04-04 01:11
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
from django.db.migrations import RunPython
from tqdm import tqdm


def update_m2m(apps, schema_editor):
    model_cls = apps.get_model("intecomm_subject.htninitialreview")
    list_model_cls = apps.get_model("intecomm_lists.htnmanagement")
    total = model_cls.objects.count()
    for obj in tqdm(model_cls.objects.all(), total=total):
        name = obj.managed_by_old
        try:
            name_obj = list_model_cls.objects.get(name=name)
        except ObjectDoesNotExist as e:
            raise ObjectDoesNotExist(
                f"During migration `update_m2m` got {e}. Value is `{name}`. "
                f"Table count: {list_model_cls.objects.count()}. Is list_data loaded?"
            )
        obj.managed_by.add(name_obj)


class Migration(migrations.Migration):
    dependencies = [
        ("intecomm_subject", "0022_historicalhtninitialreview_managed_by_other_and_more"),
    ]

    operations = [RunPython(update_m2m)]
