Django on_delete

What is Django on_delete and how do you use it? on_delete determines what happens to an object or field that references an object that got deleted. Let’s take a look at some examples:

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

class Post(models.Model):
    models.ForeignKey('Author', on_delete=models.CASCADE)

Cascade, means that when Author gets deleted, the Post that references that Author also gets deleted.

You have the following options:

  • CASCADE – the object that references the deleted object gets deleted itself
  • PROTECT – Prevents the deletion of the referenced object by raising a ProtectedError exception
  • SET_NULL – Sets the field to null. Only possible if the field is nullable, otherwise will throw an error when you try to run the application
  • SET_DEFAULT – Sets the field to its default value. Only possible if the field has a default value, otherwise will throw an error when you try to run the application
  • SET() – Can either be a value or a callable. Here’s an example:
def get_default_author():
    return Author.object.get(name='default')

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

class Post(models.Model):
    models.ForeignKey('Author', on_delete=models.SET(get_default_author))
  • DO_NOTHING – don’t do anything. If your database enforces foreign keys this will cause an IntegrityError.

What option should you use for Django on_delete?

That really depends on your specific scenario. Let’s say you are writing a shopping cart and you want to associate each order with a credit card. Even if the user deletes a credit card, you still want to keep the order around, so you would set it to SET_NULL. If on the other hand you are trying to create a site that catalogs books for authors, it wouldn’t make any sense to keep around books after an author was deleted, so you would set it to CASCADE.


Written by Eddie Svirsky

Leave a Reply