Create a drain field in an existing table

I have a table with data. Is it possible to automatically generate a drain field in an existing table? Or is there another alternative? thanks here is my table

enter image description here

+4
source share
3 answers

Using the slugify template filter, you can write a script or skip objects in the shell.

 >>> from django.template.defaultfilters import slugify >>> for obj in MyModel.objects.all(): ... obj.slug = slugify(obj.title) ... obj.save() 
+17
source

You can do this in MySQL like this: replace the name of your table with "tableName"):

 UPDATE `tableName` SET `slug`=LOWER(REPLACE( `title` , ' ' , '-' )); 

This changes names such as "This Is A Title" to bullets such as "this-is-a-title".

EDIT To handle parentheses and use two spaces:

 UPDATE `tableName` SET `slug`=LOWER( REPLACE( REPLACE( REPLACE( REPLACE( `title` , '(' , '' ) , ')' , '' ) , ' ' , ' ' ) , ' ' , '-' ) ); 
+3
source

I have a convenience model that I use in all projects for such things. I think this is 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 
+3
source

Source: https://habr.com/ru/post/1379200/


All Articles