TypeError:on_delete必须是可调用的

2024-10-02 20:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

File "C:\Users\sungk\Git\django_website\blog\models.py", line 5, in <module>     class Post(models.Model):
File "C:\Users\sungk\Git\django_website\blog\models.py", line 10, in Post     author = models.ForeignKey(User, on_delete=True)   File "C:\Users\sungk\Git\django_website\venv\lib\site-packages\django\db\models\fields\related.py", line 813, in __init__     raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable.

Tags: djangoinpygitonmodelslineblog
1条回答
网友
1楼 · 发布于 2024-10-02 20:41:51

{a1}可以而不是是{}。它应该是一个可调用的函数。通常它是作为described in the documentation的一个内置项。这可以是^{}^{}^{}^{}^{}^{}^{}

严格地说,您也可以使自己的可调用性,但这仅适用于您想要做比上面列出的更复杂的事情的情况

on_delete=…指定在删除作为作者的User对象的情况下,如何处理与相关的Post。通过使用CASDCADE,相关的Post对象将被删除:

from django.conf import settings
from django.db import models

class Post(models.Model):
    author = models.FOreignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

相关问题 更多 >