gpt4 book ai didi

python - Django 迁移不调用重写的 save() 方法?

转载 作者:行者123 更新时间:2023-12-02 06:13:55 25 4
gpt4 key购买 nike

我有一个模型SessionCategory,类似于以下内容:

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)

因此,我要添加的 name_slug 字段是 name 字段的 slugified 版本。

我运行了以下数据迁移:

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),
]

但是,如果我随后检查数据库,name_slug 字段全部为空:

enter image description here

我还反转了迁移并重新运行它,在重写的 save() 方法中设置跟踪(import ipdb; ipdb.set_trace()),但它并没有导致 Python 进入调试器,从而确认该方法未被调用。

为什么重写的 save() 方法没有被调用?我是否必须复制 generate_name_slugs 函数中的代码?

最佳答案

这应该对 SessionType 有帮助...SessionCategory 可以以同样的方式修改...

def generate_name_slugs(apps, schema_editor):
import lucy_web.models as m
for session_type in m.SessionType.objects.all():
session_type.save()

关于python - Django 迁移不调用重写的 save() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51090918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com