About on_delete Values for Foreign Keys

A rule of thumb to set the on_delete for foreign keys and one-to-one relationships is as follows:

  • If you want to avoid accidental deletions, set on_delete=models.PROTECT.
  • If the field can be blank and null, set on_delete=models.SET_NULL.
  • If the field has a default value, set on_delete=models.SET(get_default_value).
  • Otherwise, set on_delete=models.CASCADE.

Note that CASCADE deletes all children automatically if the parent is deleted.

Tips and Tricks Programming Architecture Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.