# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2019-02-11 14:56
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):
    JobMeta = apps.get_model("common", "JobMeta")
    duplicates = JobMeta.objects.values('job', 'key').annotate(Count('pk'), keys=ArrayAgg('pk')).\
        filter(pk__count__gt=1).values_list('keys', flat=True)
    for dup in duplicates:
        JobMeta.objects.filter(id__in=sorted(dup)[1:]).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('common', '0007_job_duration'),
    ]

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