What are the on_delete options for a ForeignKey (CASCADE, PROTECT, SET_NULL, etc.), and how do you decide which to use?
Last updated
on_delete(required) defines what happens to referencing rows when the target is deleted:CASCADEdeletes them,PROTECTblocks the delete withProtectedError, andSET_NULLnulls the FK (needsnull=True).SET_DEFAULT/SET(...)reassign to a default or sentinel value.DO_NOTHINGleaves integrity to the database.Decide by meaning: child can't exist without parent means
CASCADE. Child survives orphaned meansSET_NULL. Data must never be lost meansPROTECT.