[Django]-Django models ForeignKey on_delete attribute: full meaning?

25đź‘Ť

âś…

that’s the default behaviour, yes. you can change this behaviour with on_delete

to get an illustration of this, try deleting a userprofile in the admin. it first shows a warning page, listing all related objects that will also get deleted

👤second

202đź‘Ť

I’ll go through the values for on_delete as they apply to this case. As it notes in the docs, these are all in that models module, so you’d use it as models.ForeignKey(UserProfile, on_delete=models.CASCADE), etc.

These rules apply however you delete an object, whether you do it in the admin panel or working directly with the Model instance. (But it won’t take effect if you work directly with the underlying database in SQL.)

  • CASCADE: when you delete the UserProfile, all related Photos will be deleted too. This is the default. (So in answer to that aspect of your question, yes, if you delete your user account the photos will be deleted automatically.)

  • PROTECT: this will stop you from deleting a UserProfile with related Photos, raising a django.db.models.ProtectedError if you try. The idea would be that the user would need to disassociate or delete all Photos before they could delete their profile.

  • SET_NULL: when you delete the UserProfile, all associated Photos will still exist but will no longer be associated with any UserProfile. This would require null=True in the ForeignKey definition.

  • SET_DEFAULT: when you delete the UserProfile, all associated Photos will be changed to point to their default UserProfile as specified by the default attribute in the ForeignKey definition (you could use this to pass “orphaned” photos off to a certain user – but this isn’t going to be common, SET_NULL or SET() will be much more common)

  • SET(): when you delete the UserProfile, the target of the Photos’ ForeignKey will be set to the value passed in to the SET function, or what it returns if it is a callable. (Sorry, I haven’t explained that well, but the docs have an example which explains better.)

  • DO_NOTHING: when you delete the UserProfile, all related Photos will remain unaltered, thus having a broken reference, unless you have used some other SQL to take care of it.

(Also, on_delete isn’t a method. It’s an attribute of the ForeignKey field.)

👤Chris Morgan

Leave a comment