Running save() for all objects

时间:2018-12-19 11:34:09

标签: python django

I will be making a migration on my website today and I added new field(slug) and slugify method with save(). It goes like this:

def save(self, *args, **kwargs):
        self.slug = slugify(self.tag+'-'+self.title)
        super(Image, self).save(*args, **kwargs)

My model has about 50 entries and I don't want to be saving them all manually just to generate slug for all of them.

Is there a way to do it automatically?

1 个答案:

答案 0 :(得分:0)

您可以通过运行简单的迁移命令来做到这一点。

首先,您需要为您的应用生成一个空迁移。

  

python manage.py makemigrations --empty yourappname

生成的迁移文件如下所示:

# Generated by Django A.B on YYYY-MM-DD HH:MM
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
    ]

在操作列表中,您可以追加原始SQL查询。

  

operations = [       migrations.RunSQL('SQL查询以更改您的子弹字段'),   ]

例如:

migrations.RunSQL('ALTER TABLE Customer MODIFY Address char(100);'), 

PS:由于此处只有50个条目,因此您只需关注Daniel的评论。但是,在处理大量行时,我建议使用迁移方法。

希望有帮助!