File tree 2 files changed +18
-15
lines changed
2 files changed +18
-15
lines changed Original file line number Diff line number Diff line change 2
2
3
3
from django .db import migrations , models
4
4
5
+ from categories .models import Category
6
+
5
7
6
8
def make_slugs_unique (apps , schema_editor ):
7
- Category = apps .get_model ("categories" , "Category" )
8
9
duplicates = Category .tree .values ("slug" ).annotate (slug_count = models .Count ("slug" )).filter (slug_count__gt = 1 )
10
+ category_objs = []
9
11
for duplicate in duplicates :
10
12
slug = duplicate ["slug" ]
11
13
categories = Category .tree .filter (slug = slug )
12
14
count = categories .count ()
13
15
i = 0
14
16
for category in categories .all ():
15
17
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 )
18
20
i += 1
21
+ Category .objects .bulk_update (category_objs , ["slug" ])
19
22
20
23
21
24
class Migration (migrations .Migration ):
Original file line number Diff line number Diff line change @@ -25,19 +25,19 @@ def test_unique_slug_migration(self):
25
25
list (Category .tree .values_list ("slug" , flat = True )),
26
26
[
27
27
"foo" ,
28
- "foo_1 " ,
29
- "foo_2 " ,
28
+ "foo-1 " ,
29
+ "foo-2 " ,
30
30
"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 " ,
41
41
"baz" ,
42
42
],
43
43
)
You can’t perform that action at this time.
0 commit comments