26👍
✅
this is the code I have for the same situation.
models.py:
slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name')
Note the null=True which is compatible with a unique field
In my migrations, I’m adding a data migration by manually editing the migration file
0007_my_migration.py:
def migrate_data_forward(apps, schema_editor):
for instance in MyModel.objects.all():
print "Generating slug for %s"%instance
instance.save() # Will trigger slug update
def migrate_data_backward(apps, schema_editor):
pass
class Migration(migrations.Migration):
...
operations = [
migrations.AddField(
model_name='my_model',
name='slug',
field=autoslug.fields.AutoSlugField(null=True, default=None, editable=False, populate_from='name', unique=True),
preserve_default=False,
),
migrations.RunPython(
migrate_data_forward,
migrate_data_backward,
),
]
Source:stackexchange.com