Python 获取 TypeError: __init__() 缺少 1 个必需的位置参数:'on_delete' 尝试在带有条目的子表之后添加父表时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44026548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:38:40  来源:igfitidea点击:

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

pythondjangodjango-modelsdjango-2.0

提问by Christian Lisangola

I have two classes in my sqlite database, a parent table named Categorieand the child table called Article. I created first the child table class and addes entries. So first I had this:

我的 sqlite 数据库中有两个类,一个Categorie名为Article. 我首先创建了子表类并添加了条目。所以首先我有这个:

class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )

    def __str__(self):
        return self.titre

And after I have added parent table, and now my models.pylooks like this:

在我添加了父表之后,现在我models.py看起来像这样:

from django.db import models

# Create your models here.
class Categorie(models.Model):
    nom = models.CharField(max_length=30)

    def __str__(self):
        return self.nom


class Article(models.Model):
    titre=models.CharField(max_length=100)
    auteur=models.CharField(max_length=42)
    contenu=models.TextField(null=True)
    date=models.DateTimeField(
        auto_now_add=True,
        auto_now=False,
        verbose_name="Date de parution"
    )
    categorie = models.ForeignKey('Categorie')

    def __str__(self):
        return self.titre

So when I run python manage.py makemigrations <my_app_name>, I get this error:

所以当我运行时python manage.py makemigrations <my_app_name>,我收到这个错误:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 330, in execute
    django.setup()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 6, in <module>
    class Article(models.Model):
  File "C:\Users\lislis\Django\mon_site\blog\models.py", line 16, in Article
    categorie = models.ForeignKey('Categorie')
TypeError: __init__() missing 1 required positional argument: 'on_delete'

I've seen some similar issues in stackoverflow, but it seems to not be the same problem: __init__() missing 1 required positional argument: 'quantity'

我在 stackoverflow 中看到了一些类似的问题,但似乎不是同一个问题:__init__() 缺少 1 个必需的位置参数:'数量'

回答by cezar

You can change the property categorieof the class Articlelike this:

您可以像这样更改categorie类的属性Article

categorie = models.ForeignKey(
    'Categorie',
    on_delete=models.CASCADE,
)

and the error should disappear.

并且错误应该消失。

Eventually you might need another option for on_delete, check the documentation for more details:

最终你可能需要另一个选项on_delete,查看文档以获取更多详细信息:

https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey

https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey

EDIT:

编辑:

As you stated in your comment, that you don't have any special requirements for on_delete, you could use the option DO_NOTHING:

正如您在评论中所述,您对 没有任何特殊要求on_delete,您可以使用以下选项DO_NOTHING

# ...
on_delete=models.DO_NOTHING,
# ...

回答by Andrey Zhilyakov

Since Django 2.x, on_deleteis required.

由于 Django 2.x,on_delete是必需的。

Django Documentation

Django 文档

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

1.9 版后已弃用:on_delete 将成为 Django 2.0 中的必需参数。在旧版本中,它默认为 CASCADE。

回答by Javed Gouri

From Django 2.0 on_deleteis required:

从 Django 2.0on_delete是必需的:

user = models.OneToOneField(User, on_delete=models.CASCADE)

用户 = 模型。OneToOneField(用户,on_delete=models.CASCADE)

It will delete the child table data if the User is deleted. For more details check the Django documentation.

如果用户被删除,它将删除子表数据。有关更多详细信息,请查看 Django 文档。

回答by Thusitha Deepal

Since Django 2.0 the ForeignKey field requires two positional arguments:

从 Django 2.0 开始, ForeignKey 字段需要两个位置参数:

  1. the model to map to
  2. the on_delete argument
  1. 要映射到的模型
  2. on_delete 参数
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

下面是一些可以在 on_delete 中使用的方法

  1. CASCADE
  1. 级联

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

级联删除。Django 模拟 SQL 约束 ON DELETE CASCADE 的行为,并删除包含 ForeignKey 的对象

  1. PROTECT
  1. 保护

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

通过引发 ProtectedError(django.db.IntegrityError 的子类)来防止删除引用的对象。

  1. DO_NOTHING
  1. 没做什么

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

不采取行动。如果您的数据库后端强制执行参照完整性,除非您手动向数据库字段添加 SQL ON DELETE 约束,否则这将导致 IntegrityError。

you can find more about on_delete by reading the documentation.

您可以通过阅读文档找到有关 on_delete 的更多信息。

回答by Bala Kiswe

If you are using foreignkey then you have to use "on_delete=models.CASCADE" as it will eliminate the complexity developed after deleting the original element from the parent table. As simple as that.

如果您使用外键,则必须使用“on_delete=models.CASCADE”,因为它将消除从父表中删除原始元素后产生的复杂性。就如此容易。

categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)

回答by Tarun Behal

Here are available options if it helps anyone for on_delete

如果对 on_delete 有帮助,这里有可用的选项

CASCADE, DO_NOTHING, PROTECT, SET, SET_DEFAULT, SET_NULL

级联,不做,保护,设置,设置_默认,设置_空

回答by HoangYell

If you don't know which option to enter the params. Just want to keep the default value like on_delete=Nonebefore migration:

如果您不知道输入参数的选项。只想保持on_delete=None迁移前的默认值:

on_delete=models.CASCADE

on_delete=models.CASCADE

This is a code snippet in the old version:

这是旧版本的代码片段:

if on_delete is None:
    warnings.warn(
        "on_delete will be a required arg for %s in Django 2.0. Set "
        "it to models.CASCADE on models and in existing migrations "
        "if you want to maintain the current default behavior. "
        "See https://docs.djangoproject.com/en/%s/ref/models/fields/"
        "#django.db.models.ForeignKey.on_delete" % (
            self.__class__.__name__,
            get_docs_version(),
        ),
        RemovedInDjango20Warning, 2)
    on_delete = CASCADE

回答by Nir Tsabar

Had a similar problem that resolved by adding both these two parameters to ForeignKey: null=True, on_delete=models.SET_NULL

有一个类似的问题,通过将这两个参数添加到 ForeignKey 来解决:null=True, on_delete=models.SET_NULL

回答by Mayank Jaiswal

This worked for me pip install django-csvimport --upgrade

这对我有用 pip install django-csvimport --upgrade