Reputation: 518
I'm using Django 1.4 with South for migrations. I just added a slug field to one of my models and did a migration. The slug field is automatically populated for all new objects and works perfectly.
I'm wondering, is there any way to force Django to create the slug field entries for all my existing data from before the migration...
*edit I'm populating my slug field with this line in admin.py
prepopulated_fields = {"slug": ("name","price")}
Upvotes: 2
Views: 1771
Reputation: 8511
I used a South data migration that looked like this when I added a slug field to an existing table:
from django.template.defaultfilters import slugify
class Migration(DataMigration):
def forwards(self, orm):
for obj in orm.MyModel.objects.filter(slug__isnull=True):
slug = slugify(obj.name)
obj.slug = slug
suffix = 2
while orm.MyModel.objects.filter(slug=obj.slug).exists():
obj.slug = "%s-%d" % (slug, suffix)
suffix = suffix + 1
obj.save()
def backwards(self, orm):
pass # no need to change anything
Upvotes: 3