# Generated by Django 3.2.6 on 2021-09-09 12:58

from django.db import migrations, models


def set_is_gift_card_field(apps, schema_editor):
    OrderLine = apps.get_model("order", "OrderLine")
    for line in OrderLine.objects.prefetch_related(
        "variant__product__product_type"
    ).iterator():
        line.is_gift_card = (
            bool(line.variant) and line.variant.product.product_type.kind == "gift_card"
        )
        line.save(update_fields=["is_gift_card"])


class Migration(migrations.Migration):

    dependencies = [
        ("order", "0118_auto_20210913_0731"),
        ("product", "0148_producttype_type"),
    ]

    operations = [
        migrations.AddField(
            model_name="orderline",
            name="is_gift_card",
            field=models.BooleanField(null=True),
        ),
        migrations.RunPython(set_is_gift_card_field, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="orderline",
            name="is_gift_card",
            field=models.BooleanField(),
        ),
    ]

# Generated by Django 3.2.6 on 2021-09-09 12:58

from django.db import migrations, models
from django.db.models.expressions import Exists, OuterRef


def set_is_gift_card_field(apps, schema_editor):
    OrderLine = apps.get_model("order", "OrderLine")
    ProductType = apps.get_model("product", "ProductType")
    Product = apps.get_model("product", "Product")
    ProductVariant = apps.get_model("product", "ProductVariant")

    product_types = ProductType.objects.filter(kind="gift_card")
    products = Product.objects.filter(
        Exists(product_types.filter(pk=OuterRef("product_type_id")))
    )
    variants = ProductVariant.objects.filter(
        Exists(products.filter(pk=OuterRef("product_id")))
    )

    gift_card_lines = OrderLine.objects.filter(
        Exists(variants.filter(pk=OuterRef("variant_id")))
    )
    gift_card_lines.update(is_gift_card=True)

    lines = OrderLine.objects.exclude(
        Exists(variants.filter(pk=OuterRef("variant_id")))
    )
    lines.update(is_gift_card=False)


class Migration(migrations.Migration):

    dependencies = [
        ("order", "0118_auto_20210913_0731"),
        ("product", "0148_producttype_type"),
    ]

    operations = [
        migrations.AddField(
            model_name="orderline",
            name="is_gift_card",
            field=models.BooleanField(null=True),
        ),
        migrations.RunPython(set_is_gift_card_field, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="orderline",
            name="is_gift_card",
            field=models.BooleanField(),
        ),
    ]

Optimize Order line is gift card migration (#8427)