Reputation: 1961
I have table with data. Is it possible slug field automatically generated on existing table? Or is there any other alternative? Thanks Here is my table
Upvotes: 4
Views: 3369
Reputation: 22841
I have a convenience model I use in all projects for these kinds of things. I think it's a good example of how to do what you want.
from django.template.defaultfilters import slugify
class NameAndSlug(models.Model):
'''
convenience model for things that are just names
'''
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField()
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
"""
Slugify name if it doesn't exist. IMPORTANT: doesn't check to see
if slug is a dupe!
"""
if not self.slug:
self.slug = slugify(self.name)
super(NameAndSlug, self).save(*args, **kwargs)
class Meta:
abstract = True
Upvotes: 4
Reputation: 308999
Using the slugify
template filter, you can write a script, or loop through the objects in the shell.
>>> from django.template.defaultfilters import slugify
>>> for obj in MyModel.objects.all():
... obj.slug = slugify(obj.title)
... obj.save()
Upvotes: 18
Reputation: 1660
You can do this in MySQL like so (substitute the name of your table for "tableName"):
UPDATE `tableName` SET `slug`=LOWER(REPLACE( `title` , ' ' , '-' ));
This changes titles like "This Is A Title" to slugs like "this-is-a-title".
EDIT To handle parentheses and remove double spaces use:
UPDATE `tableName` SET `slug`=LOWER( REPLACE( REPLACE( REPLACE( REPLACE( `title` , '(' , '' ) , ')' , '' ) , ' ' , ' ' ) , ' ' , '-' ) );
Upvotes: 3