Skip to content

Commit

Permalink
make datamigration for non-unique slugs, test the migration
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrDlouhy committed Mar 13, 2020
1 parent 0484bc9 commit da066f9
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
16 changes: 16 additions & 0 deletions categories/migrations/0004_unique_category_slug.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,29 @@
from django.db import migrations, models


def make_slugs_unique(apps, schema_editor):
Category = apps.get_model('categories', 'Category')
duplicates = Category.tree.values('slug').annotate(slug_count=models.Count('slug')).filter(slug_count__gt=1)
for duplicate in duplicates:
slug = duplicate['slug']
categories = Category.tree.filter(slug=slug)
count = categories.count()
i = 0
for category in categories.all():
if i != 0:
category.slug = "%s_%s" % (slug, str(i).zfill(len(str(count))))
category.save()
i += 1


class Migration(migrations.Migration):

dependencies = [
('categories', '0003_auto_20200306_1050'),
]

operations = [
migrations.RunPython(make_slugs_unique, reverse_code=migrations.RunPython.noop),
migrations.AlterField(
model_name='category',
name='slug',
Expand Down
44 changes: 44 additions & 0 deletions categories/tests/test_migrations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import sys


if (sys.version_info >= (3, 0)):
from django_test_migrations.contrib.unittest_case import MigratorTestCase

class TestMigrations(MigratorTestCase):

migrate_from = ('categories', '0003_auto_20200306_1050')
migrate_to = ('categories', '0004_unique_category_slug')

def prepare(self):
Category = self.old_state.apps.get_model('categories', 'Category')
Category.tree.create(slug='foo', lft=0, rght=0, tree_id=0, level=0)
Category.tree.create(slug='foo', lft=0, rght=0, tree_id=0, level=0)
Category.tree.create(slug='foo', lft=0, rght=0, tree_id=0, level=0)
for i in range(1, 12):
Category.tree.create(slug='bar', lft=0, rght=0, tree_id=0, level=0)
Category.tree.create(slug='baz', lft=0, rght=0, tree_id=0, level=0)
assert Category.tree.count() == 15

def test_unique_slug_migration(self):
Category = self.new_state.apps.get_model('categories', 'Category')

self.assertListEqual(
list(Category.tree.values_list('slug', flat=True)),
[
'foo',
'foo_1',
'foo_2',
'bar',
'bar_01',
'bar_02',
'bar_03',
'bar_04',
'bar_05',
'bar_06',
'bar_07',
'bar_08',
'bar_09',
'bar_10',
'baz',
],
)
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ deps=
coverage
pillow
ipdb
!py27: django-test-migrations
-r{toxinidir}/requirements.txt

commands=
Expand Down

0 comments on commit da066f9

Please sign in to comment.