# Generated by Django 5.2.9 on 2025-12-16 15:15

from django.db import migrations, models



def cleanup_duplicates(apps, schema_editor):
    RelatedInstrumentThroughModel = apps.get_model('wbfdm.RelatedInstrumentThroughModel')
    for row in RelatedInstrumentThroughModel.objects.values("instrument", "related_instrument", "related_type").annotate(c=models.Count("*")).filter(c__gt=1):
        qs = RelatedInstrumentThroughModel.objects.filter(
            instrument=row["instrument"],
            related_instrument=row["related_instrument"],
            related_type=row["related_type"]
        )
        qs.exclude(id=qs.first().id).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('wbfdm', '0036_alter_relatedinstrumentthroughmodel_unique_together_and_more'),
    ]

    operations = [
        migrations.RunPython(cleanup_duplicates),
        migrations.AddConstraint(
            model_name='relatedinstrumentthroughmodel',
            constraint=models.UniqueConstraint(fields=('instrument', 'related_instrument', 'related_type'), name='unique_instrument_relationship'),
        ),
        migrations.AddConstraint(
            model_name='relatedinstrumentthroughmodel',
            constraint=models.UniqueConstraint(condition=models.Q(('is_primary', True)), fields=('instrument', 'related_type'), name='unique_primary_instrument_relationship'),
        ),
    ]
