# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-08-28 13:27
from __future__ import unicode_literals

from django.contrib.postgres.aggregates import ArrayAgg
from django.db import migrations
from django.db.models import Count


def delete_duplicates(apps, schema_editor):
    DataMeta = apps.get_model("common", "DataMeta")
    duplicates = DataMeta.objects.values('data', 'key').annotate(Count('pk'), keys=ArrayAgg('pk')). \
        filter(pk__count__gt=1).values_list('keys', flat=True)
    for dup in duplicates:
        DataMeta.objects.filter(id__in=sorted(dup)[1:]).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('common', '0016_regression_person'),
    ]

    operations = [
        migrations.RunPython(delete_duplicates),
        migrations.AlterUniqueTogether(
            name='datameta',
            unique_together=set([('data', 'key')]),
        ),
    ]
