Skip to content

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

Optimize order 0150_update_authorize_and_charge_status migration (#12083)

Tomasz Szymańskidfef31cc4020
diff --git a/saleor/order/migrations/0150_update_authorize_and_charge_status.py b/saleor/order/migrations/0150_update_authorize_and_charge_status.py
index e4d88742f3..f2a82765ad 100644
--- a/saleor/order/migrations/0150_update_authorize_and_charge_status.py
+++ b/saleor/order/migrations/0150_update_authorize_and_charge_status.py
@@ -1,35 +1,43 @@
# Generated by Django 3.2.13 on 2022-05-19 11:21
-from django.db import migrations, models
+from django.db import migrations
+from django.db.models import F, Case, When, Value
-def update_authorize_status(apps, _schema_editor):
+def update_authorize_and_charge_status(apps, _schema_editor):
Order = apps.get_model("order", "Order")
- order_query = Order.objects.annotate(
- sum_authorized=models.F("total_authorized_amount")
- + models.F("total_charged_amount")
- )
- order_query.filter(
- sum_authorized__gt=0, sum_authorized__lt=models.F("total_gross_amount")
- ).update(authorize_status="partial")
- order_query.filter(sum_authorized__gte=models.F("total_gross_amount")).update(
- authorize_status="full"
- )
-
-
-def update_charge_status(apps, _schema_editor):
- Order = apps.get_model("order", "Order")
- Order.objects.filter(
- total_charged_amount__gt=0,
- total_charged_amount__lt=models.F("total_gross_amount"),
- ).update(charge_status="partial")
-
- Order.objects.filter(total_charged_amount=models.F("total_gross_amount")).update(
- charge_status="full"
+ Order.objects.annotate(
+ sum_authorized=F("total_authorized_amount") + F("total_charged_amount"),
+ ).update(
+ authorize_status=Case(
+ When(
+ sum_authorized__gt=0,
+ sum_authorized__lt=F("total_gross_amount"),
+ then=Value("partial"),
+ ),
+ When(
+ sum_authorized__gte=F("total_gross_amount"),
+ then=Value("full"),
+ ),
+ default="authorize_status",
+ ),
+ charge_status=Case(
+ When(
+ total_charged_amount__gt=0,
+ total_charged_amount__lt=F("total_gross_amount"),
+ then=Value("partial"),
+ ),
+ When(
+ total_charged_amount=F("total_gross_amount"),
+ then=Value("full"),
+ ),
+ When(
+ total_charged_amount__gt=F("total_gross_amount"),
+ then=Value("overcharged"),
+ ),
+ default="charge_status",
+ ),
)
- Order.objects.filter(
- total_charged_amount__gt=models.F("total_gross_amount")
- ).update(charge_status="overcharged")
class Migration(migrations.Migration):
@@ -39,9 +47,6 @@ class Migration(migrations.Migration):
operations = [
migrations.RunPython(
- update_authorize_status, reverse_code=migrations.RunPython.noop
- ),
- migrations.RunPython(
- update_charge_status, reverse_code=migrations.RunPython.noop
+ update_authorize_and_charge_status, reverse_code=migrations.RunPython.noop
),
]