In Django, when you define a ForeignKey, the on_delete argument is required. It tells Django what to do when the referenced object is deleted.

Syntax:

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

If the Author is deleted, Django will follow the rule defined in on_delete to decide what happens to the related Book.

Common on_delete Options

Option Description
CASCADE Delete the related object too (e.g., delete all books if author is deleted)
PROTECT Prevent deletion of the referenced object; raises ProtectedError
SET_NULL Set the foreign key to NULL (requires null=True)
SET_DEFAULT Set to the field’s default value
SET(<function>)</function> Set to the result of a callable (e.g., SET(get_sentinel_user))
DO_NOTHING Do nothing (may cause database errors if not handled carefully)
RESTRICT (Django 3.1+) Prevent deletion if any related object exists

Example:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)

In this case, if the author is deleted, the book’s author field is set to NULL.

Frequently Asked Questions (FAQs)

Q1. Is on_delete required in Django?

A: Yes. Since Django 2.0, it’s mandatory to define the on_delete behavior when using a ForeignKey or OneToOneField.

Q2. What’s the safest on_delete option?

A: PROTECT is generally safest—it prevents accidental deletion of referenced objects. RESTRICT (in Django 3.1+) is similar but more flexible with complex rules.

Q3. Can I use SET_NULL without null=True?

A: No. If you use SET_NULL, you must also declare null=True on the field, or Django will raise an error.

Q4. What’s the difference between CASCADE and SET_NULL?

A:

  • CASCADE deletes related objects too.
     

  • SET_NULL keeps related objects but clears the reference to the deleted object.

Q5. What happens if I use DO_NOTHING?

A: Django won’t do anything. But if the database doesn’t support empty foreign keys, it will throw an IntegrityError. You’ll need to handle the deletion manually.

Q6. What’s a real-world use case for SET(get_sentinel_user)?

A: Common in user models when a user is deleted, assign their content to a placeholder “anonymous” or “deleted” user instead of deleting it.