# Generated by Django 2.2.7 on 2020-01-28 17:46

from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


def make_relations(apps, schemaeditor):
    PartnerToEstablishment = apps.get_model('partner', 'PartnerToEstablishment')
    Partner = apps.get_model('partner', 'Partner')
    Establishment = apps.get_model('establishment', 'Establishment')
    touched_partners_ids = []
    for establishment in Establishment.objects.filter(partners__isnull=False):
        for related_partner in establishment.partners.all():
            real_partner = Partner.objects.filter(name=related_partner.name, type=related_partner.type,
                                                  url=related_partner.url).first()
            touched_partners_ids.append(related_partner.pk)
            PartnerToEstablishment(establishment=establishment, partner=real_partner, partner_bind_date=real_partner.created).save()


class Migration(migrations.Migration):

    dependencies = [
        ('establishment', '0083_establishment_instagram'),
        ('partner', '0003_auto_20191121_1059'),
    ]

    operations = [
        migrations.CreateModel(
            name='PartnerToEstablishment',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('partner_bind_date', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date partner binded')),
                ('establishment', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='establishment.Establishment')),
                ('partner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='partner.Partner')),
            ],
        ),
        migrations.AddField(
            model_name='partner',
            name='establishments',
            field=models.ManyToManyField(null=True, related_name='new_partners', through='partner.PartnerToEstablishment', to='establishment.Establishment', verbose_name='Establishments'),
        ),
        migrations.RunPython(make_relations, migrations.RunPython.noop),
    ]
