Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Optimize queries in migration order 0139_fulfil_orderline_token_old_id_created_at (#11932)

Krzysztof Kwaśniakcfcda3414dcc
diff --git a/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py b/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py
index 65a37b7205..4a6507a420 100644
--- a/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py
+++ b/saleor/order/migrations/0139_fulfil_orderline_token_old_id_created_at.py
@@ -1,30 +1,31 @@
# Generated by Django 3.2.12 on 2022-04-11 12:32
from django.db import migrations
-from django.db.models import F, OuterRef, Subquery
+from django.db.models import F, OuterRef, Subquery, Case, When
from django.contrib.postgres.functions import RandomUUID
from django.contrib.postgres.operations import CryptoExtension
-def set_order_line_token_and_created_at(apps, _schema_editor):
+def set_order_line_old_id_and_order_line_token_and_created_at(apps, _schema_editor):
OrderLine = apps.get_model("order", "OrderLine")
Order = apps.get_model("order", "Order")
- OrderLine.objects.filter(token__isnull=True).update(
- token=RandomUUID(),
- created_at=Subquery(
- Order.objects.filter(lines=OuterRef("id")).values("created_at")[:1]
+ OrderLine.objects.update(
+ old_id=F("id"),
+ token=Case(When(token__isnull=True, then=RandomUUID()), default="token"),
+ created_at=Case(
+ When(
+ token__isnull=True,
+ then=Subquery(
+ Order.objects.filter(lines=OuterRef("id")).values("created_at")[:1]
+ ),
+ ),
+ default="created_at",
),
)
-def set_order_line_old_id(apps, schema_editor):
- OrderLine = apps.get_model("order", "OrderLine")
- OrderLine.objects.all().update(old_id=F("id"))
-
-
class Migration(migrations.Migration):
-
dependencies = [
("order", "0138_add_orderline_token_old_id_created_at"),
]
@@ -32,10 +33,7 @@ class Migration(migrations.Migration):
operations = [
CryptoExtension(),
migrations.RunPython(
- set_order_line_token_and_created_at,
+ set_order_line_old_id_and_order_line_token_and_created_at,
migrations.RunPython.noop,
),
- migrations.RunPython(
- set_order_line_old_id, reverse_code=migrations.RunPython.noop
- ),
]