From ba2d654f158e17e8d3de074a78cab42515c54b09 Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Thu, 23 Jan 2025 22:03:02 -0300 Subject: [PATCH] feat(accounts): make account names unique --- .../0007_make_account_names_unique.py | 38 +++++++++++++++++++ .../migrations/0008_alter_account_name.py | 18 +++++++++ 2 files changed, 56 insertions(+) create mode 100644 app/apps/accounts/migrations/0007_make_account_names_unique.py create mode 100644 app/apps/accounts/migrations/0008_alter_account_name.py diff --git a/app/apps/accounts/migrations/0007_make_account_names_unique.py b/app/apps/accounts/migrations/0007_make_account_names_unique.py new file mode 100644 index 0000000..e570246 --- /dev/null +++ b/app/apps/accounts/migrations/0007_make_account_names_unique.py @@ -0,0 +1,38 @@ +from django.db import migrations, models + + +def make_names_unique(apps, schema_editor): + Account = apps.get_model("accounts", "Account") + + # Get all accounts ordered by id + accounts = Account.objects.all().order_by("id") + + # Track seen names + seen_names = {} + + for account in accounts: + original_name = account.name + counter = seen_names.get(original_name, 0) + + while account.name in seen_names: + counter += 1 + account.name = f"{original_name} ({counter})" + + seen_names[account.name] = counter + account.save() + + +def reverse_migration(apps, schema_editor): + # Can't restore original names, so do nothing + pass + + +class Migration(migrations.Migration): + + dependencies = [ + ("accounts", "0006_rename_archived_account_is_archived_and_more"), + ] + + operations = [ + migrations.RunPython(make_names_unique, reverse_migration), + ] diff --git a/app/apps/accounts/migrations/0008_alter_account_name.py b/app/apps/accounts/migrations/0008_alter_account_name.py new file mode 100644 index 0000000..a6a5cfc --- /dev/null +++ b/app/apps/accounts/migrations/0008_alter_account_name.py @@ -0,0 +1,18 @@ +# Generated by Django 5.1.5 on 2025-01-24 00:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('accounts', '0007_make_account_names_unique'), + ] + + operations = [ + migrations.AlterField( + model_name='account', + name='name', + field=models.CharField(max_length=255, unique=True, verbose_name='Name'), + ), + ]