Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate slug field in existing table

Tags:

python

django

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

enter image description here

like image 205
no_freedom Avatar asked Nov 29 '22 03:11

no_freedom


2 Answers

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()
like image 78
Alasdair Avatar answered Dec 06 '22 17:12

Alasdair


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
like image 38
Tom Avatar answered Dec 06 '22 17:12

Tom