且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

级联更新和删除wih django

更新时间:2023-02-02 23:20:46

查看 ForeignKey docs。它说:

Look at the ForeignKey docs. It says:


当一个ForeignKey引用的对象被删除时,Django默认模拟SQL约束在DELETE CASCADE上的行为,删除包含ForeignKey的对象。可以通过指定on_delete参数来覆盖此行为。

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.

所以默认行为是级联在删除上,但您可以通过指定如下:

So the default behavior is to cascade on delete, but you can change it by specifying something like this:

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