# Generated by Django 2.0.5 on 2018-07-15 16:06

from django.db import migrations
from django.db.models import OuterRef, Subquery
import django_countries.fields


def update_country_from_airport(apps, schema_editor):
    Person = apps.get_model('workshops', 'Person')
    Airport = apps.get_model('workshops', 'Airport')

    persons = Person.objects.exclude(airport=None)
    # This special construction uses Subquery abilities introduced in
    # Django v1.11; they make possible forcing Django ORM to use SQL subqueries.
    # https://docs.djangoproject.com/en/2.0/ref/models/expressions/#subquery-expressions

    # First, a list of airports corresponding to person IDs (to be grabbed from
    # outer query) is generated.
    airports = Airport.objects.filter(person=OuterRef('pk'))
    # Then a subquery using only one column and producing only one row.
    sq = Subquery(airports.values('country')[:1])
    # Finally, the update.
    persons.update(country=sq)


class Migration(migrations.Migration):

    dependencies = [
        ('workshops', '0143_auto_20180712_1337'),
    ]

    operations = [
        migrations.AddField(
            model_name='person',
            name='country',
            field=django_countries.fields.CountryField(blank=True, default='', help_text="Person's country of residence.", max_length=2),
        ),
        migrations.RunPython(update_country_from_airport),
    ]
