Skip to main content
 首页 » 编程设计

python之将Django项目移植到Python 3和Django 2时的迁移问题

2024年11月24日25softidea

我一直在将一个 Django 项目移植到 Python 3 和 Django 2。我不得不按照 Django 2 的要求将 on_delete 添加到我所有的带有外键的模型中。现在我已经尝试对这些更改进行迁移TypeError:__init__() 缺少 1 个必需的位置参数:'on_delete'。

它引用的文件是 0002 迁移文件,而不是已更新的模型文件。我不确定如何解决这个问题。我已经尝试伪造迁移,但我仍然遇到同样的错误。

我不确定为什么它认为数据库不存在,我已经检查过并且一切都完好无损并且在 Postgres 中工作。有什么想法吗?

请您参考如下方法:

自 ForeignKey fields [Django-doc]和 OneToOneField fields fields现在有一个必需的 on_delete parameter .

这在 release notes of Django-2.0 under Features removed in 2.0 中指定:

The on_delete argument for ForeignKey and OneToOneField is now required in models and migrations. Consider squashing migrations so that you have fewer of them to update.

因此,您应该检查迁移文件中的 ForeignKey 和 OneToOneField,并添加一个 on_delete 参数,例如:

class Migration(migrations.Migration): 
 
    initial = False 
 
    dependencies = [ 
        ('app', '0001_initial'), 
    ] 
 
    operations = [ 
        migrations.CreateModel( 
            name='Model', 
            fields=[ 
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 
                ('some_foreignkey', models.ForeignKey(<b>on_delete=django.db.models.deletion.CASCADE</b>, to='app.OtherModel')), 
            ], 
        ), 
    ]

您应该检查 documentation on the on_delete parameter查看哪种删除策略最适合每种情况。选项是,在编写 CASCADE 时,PROTECT,SET_NULL,SET_DEFAULT,SET( ..),不要做。

如果您没有在预 中指定 on_delete版本,它默认为 CASCADE。因此,如果您想要相同的行为,您应该添加 on_delete=models.CASCADE。这在 1.11 version of the documentation on on_delete 中有说明。 :

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.