8

I have a model SessionCategory which is similar to the following:

from django.db import models
from django.utils.text import slugify


class SessionCategory(models.Model):
    name = models.CharField(max_length=255, unique=True)
    name_slug = models.CharField(max_length=255, null=True)

    def save(self, *args, **kwargs):
        if not self.name_slug:
            self.name_slug = slugify(self.name)
        super().save(*args, **kwargs)

So the name_slug field, which I'd like to add, is a slugified version of the name field.

I've run the following data migration:

from __future__ import unicode_literals

from django.db import migrations, models


def generate_name_slugs(apps, schema_editor):
    SessionType = apps.get_model('lucy_web', 'SessionType')
    for session_type in SessionType.objects.all():
        session_type.save()


class Migration(migrations.Migration):

    dependencies = [
        ('lucy_web', '0163_auto_20180627_1309'),
    ]

    operations = [
        migrations.AddField(
            model_name='sessioncategory',
            name='name_slug',
            field=models.CharField(max_length=255, null=True),
        ),
        migrations.RunPython(
            generate_name_slugs,
            reverse_code=migrations.RunPython.noop),
    ]

However, if I check the database afterward, the name_slug fields are all null:

enter image description here

I've also reversed the migration and re-run it setting a trace (import ipdb; ipdb.set_trace()) in the overridden save() method, but it didn't cause Python to drop into the debugger, confirming that that method is not called.

Why is the overridden save() method not getting called? Do I have to replicate the code in the generate_name_slugs function?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

1 Answers1

2

This should help for SessionType... SessionCategory can be modified the same way...

def generate_name_slugs(apps, schema_editor):
    import lucy_web.models as m
    for session_type in m.SessionType.objects.all():
        session_type.save()
djvg
  • 11,722
  • 5
  • 72
  • 103
Milon
  • 21
  • 1
  • 6