Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any other option for on_delete other than models.CASCADE for a ForeignKey in Django models?

Why is the on_delete property of a ForeignKey in a Django model not default? That should be the case if there is no other option other than models.CASCADE. Is there any other option for the on_delete property?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, there are multiple builtin handlers for the on_delete=… parameter [Django-doc]. The documentation specifies:

  • CASCADE Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object
    containing the ForeignKey. (…)

  • PROTECT: Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  • RESTRICT: Prevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError). Unlike
    PROTECT, deletion of the referenced object is allowed if it also
    references a different object that is being deleted in the same
    operation, but via a CASCADE relationship. (…)

  • SET_NULL: Set the ForeignKey null; this is only possible if null is True.

  • SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.

  • SET(…): Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. (…)

  • DO_NOTHING: Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you
    manually add an SQL ON DELETE constraint to the database field.

Furthermore you can also write your own handler for the on_delete=… parameter. For example in this article, I discuss implementing a handler that is to some extent the same as a SET(…) but the callable it uses accepts as parameter the object that should be updated.

In the "early days", and prior, you did not have to set an on_delete=… parameter: CASCADE was used as default value. But this makes it rather implicit what should happen in case the referenced object is removed, so later they made the parameter mandatory.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading