[Python] Django migration not calling overridden save() method?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    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:

    [​IMG]

    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?

    Continue reading...

Compartilhe esta Página