Django模型字段:在添加新字段时,基于同一模型中的另一个字段添加默认值

4

我有这个字段,

job_created = models.DateTimeField(auto_now_add=True)

现在我想添加这样的内容,如何基于post_created本身设置默认值。我希望第一个last_modified是工作创建时,我想要像这样的东西。
last_modified = models.DateTimeField(auto_now=True, default = post_created)

如果我在运行迁移时提供一个默认值,该怎么做?

1个回答

8
基本上你不能这样做,但是你可以创建一个数据迁移。 (了解数据迁移)
def set_last_modified(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')

    for obj in MyModel.objects.all():
        obj.last_modified = obj.post_created
        obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', 'previous_migration'),
    ]

    operations = [
        # Doesn't need to do anything in reverse, models have not been changed
        migrations.RunPython(set_last_modified, migrations.RunPython.noop)
    ]

您需要运行以下命令获取此迁移的模板:
migrations --empty yourappname

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接