# Generated by Django 3.2.11 on 2022-07-22 15:25
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
from tqdm import tqdm

from meta_pharmacy.constants import METFORMIN


def update_rx_missing_medication(apps, schema_editor):
    medication_model_cls = apps.get_model("edc_pharmacy.medication")
    rx_model_cls = apps.get_model("edc_pharmacy.rx")
    try:
        medication = medication_model_cls.objects.get(name=METFORMIN)
    except ObjectDoesNotExist:
        pass
    else:
        total = rx_model_cls.objects.filter(medications__isnull=True).count()
        for obj in tqdm(rx_model_cls.objects.filter(medications__isnull=True), total=total):
            if not obj.medications.all().exists():
                obj.medications.add(medication)


class Migration(migrations.Migration):
    dependencies = [
        ("meta_subject", "0131_auto_20220722_0411"),
    ]

    operations = [migrations.RunPython(update_rx_missing_medication)]
