[Fixed]-Django model save – override method not invoked during migrations

2πŸ‘

βœ…

It happens because migrations don’t call your save method.

I think save method is not the best place for generate slug. Will be better to use AutoSlugField or signals.

1. signals:

In your case you may use signal pre_save.

Example:

@receiver(pre_save, sender=MyModel)
def my_handler(sender, **kwargs):
    my_model = kwargs.get('instance')
    if my_model.column2:
        my_model.slug = slugify(my_model.column1 + " " + my_model.column2)
    else:
        my_model.slug = slugify(my_model.column1)
    print my_model.slug

2. AutoSlugField:

It’s not a standard field but a lot of libraries implement it. I use AutoSlugField from django-extensions. This field uses signals too.

Example:

slug = AutoSlugField(populate_from=("column1", "column2"))

3. save method and migrations

But if you still want to use a save method to generating slug I’d recommend you create data migration and add slugs manually.

Data Migrations django >= 1.7

Data Migrations south

12πŸ‘

Custom model methods are not available during migrations.

Instead, you can run put code in your RunPython function that modifies your model instances the way the custom save() would have.

References:

πŸ‘€Flimm

Leave a comment