Skip to content

Commit 150f6ed

Browse files
committed
[PATCH] Optimize slug duplication migration
1 parent 6d4fa27 commit 150f6ed

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

categories/migrations/0005_unique_category_slug.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,23 @@
22

33
from django.db import migrations, models
44

5+
from categories.models import Category
6+
57

68
def make_slugs_unique(apps, schema_editor):
7-
Category = apps.get_model("categories", "Category")
89
duplicates = Category.tree.values("slug").annotate(slug_count=models.Count("slug")).filter(slug_count__gt=1)
10+
category_objs = []
911
for duplicate in duplicates:
1012
slug = duplicate["slug"]
1113
categories = Category.tree.filter(slug=slug)
1214
count = categories.count()
1315
i = 0
1416
for category in categories.all():
1517
if i != 0:
16-
category.slug = "%s_%s" % (slug, str(i).zfill(len(str(count))))
17-
category.save()
18+
category.slug = "{}-{}".format(slug, str(i).zfill(len(str(count))))
19+
category_objs.append(category)
1820
i += 1
21+
Category.objects.bulk_update(category_objs, ["slug"])
1922

2023

2124
class Migration(migrations.Migration):

categories/tests/test_migrations.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,19 @@ def test_unique_slug_migration(self):
2525
list(Category.tree.values_list("slug", flat=True)),
2626
[
2727
"foo",
28-
"foo_1",
29-
"foo_2",
28+
"foo-1",
29+
"foo-2",
3030
"bar",
31-
"bar_01",
32-
"bar_02",
33-
"bar_03",
34-
"bar_04",
35-
"bar_05",
36-
"bar_06",
37-
"bar_07",
38-
"bar_08",
39-
"bar_09",
40-
"bar_10",
31+
"bar-01",
32+
"bar-02",
33+
"bar-03",
34+
"bar-04",
35+
"bar-05",
36+
"bar-06",
37+
"bar-07",
38+
"bar-08",
39+
"bar-09",
40+
"bar-10",
4141
"baz",
4242
],
4343
)

0 commit comments

Comments
 (0)