From 146bbc353936e99d7977ec0188e101117573dde6 Mon Sep 17 00:00:00 2001 From: Egor fureunoir Gorbunov Date: Tue, 6 May 2025 17:13:33 +0300 Subject: [PATCH] Fix duplicate human_readable_id values in Order model This migration resolves duplicate human_readable_id values by assigning unique IDs where necessary. A data migration script is introduced to identify and fix duplicates before altering the field. --- .../0018_alter_order_human_readable_id.py | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/core/migrations/0018_alter_order_human_readable_id.py b/core/migrations/0018_alter_order_human_readable_id.py index 2b5d8375..af9a1d8b 100644 --- a/core/migrations/0018_alter_order_human_readable_id.py +++ b/core/migrations/0018_alter_order_human_readable_id.py @@ -1,9 +1,31 @@ -# Generated by Django 5.1.8 on 2025-05-06 13:58 +from django.db.models import Count import core.utils from django.db import migrations, models +def fix_duplicates(apps, schema_editor): + Order = apps.get_model("core", "Order") + duplicates = ( + Order.objects.values("human_readable_id") + .annotate(count=Count("id")) + .filter(count__gt=1) + ) + for duplicate in duplicates: + h_id = duplicate["human_readable_id"] + orders = Order.objects.filter(human_readable_id=h_id).order_by("id") + for order in orders[1:]: + new_id = order.human_readable_id + while Order.objects.filter(human_readable_id=new_id).exists(): + from core.utils import generate_human_readable_id + new_id = generate_human_readable_id() + order.human_readable_id = new_id + order.save() + + +def reverse_func(apps, schema_editor): + pass + class Migration(migrations.Migration): dependencies = [ @@ -11,6 +33,7 @@ class Migration(migrations.Migration): ] operations = [ + migrations.RunPython(fix_duplicates, reverse_func), migrations.AlterField( model_name='order', name='human_readable_id',