Django: generate slug field data for existing records in database

Some time ago I created a Django model:

class Product(models.Model): name = models.CharField(verbose_name=_('Nome'), max_length=100) description = models.CharField(verbose_name=_('Descrizione'), blank=True, default="") 

Now I would like to insert the slug field:

 class Product(models.Model): name = models.CharField(verbose_name=_('Nome'), max_length=100) slug = AutoSlugField(populate_from='name', unique=True) description = models.CharField(verbose_name=_('Descrizione'), blank=True, default="") 

My problem is that when I create a hyphen, Django asks me to insert a default value for the slug field.

My idea is to generate slug during migration for existing records in the database, is there a way to do this?

Thanks!

+7
django model
source share
1 answer

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 value, compatible with the unique field. In my migrations, I add data migration manually by 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, ), ] 
+9
source share

All Articles