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

标签 python django django-2.0

我一直在将一个 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.

因此,您应该检查迁移文件中的 ForeignKeyOneToOneField,并添加一个 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 时,PROTECTSET_NULLSET_DEFAULTSET( ..)不要做

如果您没有在预 中指定 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.

关于python - 将Django项目移植到Python 3和Django 2时的迁移问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084552/

相关文章:

python - 嵌套的 "and/or"if 语句

python - 在 PyQt 中关闭 QTextEdit 时连接到方法/函数

python - 在处理包/蛋时,zc.buildout 是否比 pip 提供更多

mysql - 使用 powershell 开发脚本启动 docker

django - path() 和 re_path() 有什么区别?

python - 在嵌套的 Django 模型中创建查询并将结果分组到 Django 中

python - 在 forms.py 的 admin.py 中包含一个 ModelForm

python - 在 Django 中查找相关字段的优雅方式

python - Django - TabularInline 没有添加按钮

python - Django 奇怪的 SlugField 验证,在 clean() 之前未引发错误,返回未清理的数据