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.
This commit is contained in:
parent
ca60bf09a6
commit
146bbc3539
1 changed files with 24 additions and 1 deletions
|
|
@ -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
|
import core.utils
|
||||||
from django.db import migrations, models
|
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):
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
|
@ -11,6 +33,7 @@ class Migration(migrations.Migration):
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
||||||
|
migrations.RunPython(fix_duplicates, reverse_func),
|
||||||
migrations.AlterField(
|
migrations.AlterField(
|
||||||
model_name='order',
|
model_name='order',
|
||||||
name='human_readable_id',
|
name='human_readable_id',
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue