from pathlib import Path from django.db import migrations, models from django.template.defaultfilters import slugify def rename_photos(apps, schema_editor): Photo = apps.get_model("photologue", "Photo") taken_slugs = set(Photo.objects.values_list("slug", flat=True)) for photo in Photo.objects.order_by("pk"): new_title = Path(photo.image.name).stem base_slug = slugify(new_title) taken_slugs.discard(photo.slug) if base_slug in taken_slugs: counter = 2 while f"{base_slug}-{counter}" in taken_slugs: counter += 1 new_slug = f"{base_slug}-{counter}" else: new_slug = base_slug taken_slugs.add(new_slug) photo.title = new_title photo.slug = new_slug photo.save() class Migration(migrations.Migration): dependencies = [ ('photologue', '0006_allow_duplicate_gallery_titles'), ] operations = [ migrations.AlterField( model_name='photo', name='title', field=models.CharField(max_length=250, verbose_name='title'), ), migrations.RunPython(rename_photos, migrations.RunPython.noop), ]