Skip to main content
 首页 » 编程设计

python之使用 Django 级联更新和删除

2025年05月04日36wuhuacong

我在模型 api 中找不到级联更新或删除的选项。我想知道是否有手册可以帮助我在同步数据库时传递此数据库选项。

有什么想法吗?

请您参考如下方法:

查看ForeignKey文档。它说:

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument.

所以默认行为是级联删除,但您可以通过指定如下内容来更改它:

class Foobar(models.Model): 
    user = models.ForeignKey(User, on_delete=models.SET(User.objects.get_or_create(username="foooobarrrr")[0]))