SQLon_delete的删除选项操作分析

there are 6 possible actions to take when such event occurs:

cascade: when the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). sql equivalent:cascade.

protect: forbid the deletion of the referenced object. to delete it you will have to delete all objects that reference it manually. sql equivalent:restrict.

set_null: set the reference to null (requires the field to be nullable). for instance, when you delete a user, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. sql equivalent:set null.

set_default: set the default value. sql equivalent:set default.

set(…): set a given value. this one is not part of the sql standard and is entirely handled by django.

do_nothing: probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn’t exist). sql equivalent:no action.

source:django documentation

see alsothe documentation of postgresqlfor instance.

in most cases,cascadeis the expected behaviour, but for every foreignkey, you should always ask yourself what is the expected behaviour in this situation.protectandset_nullare often useful. settingcascadewhere it should not, can potentially delete all your database in cascade, by simply deleting a single user.

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐