Detailed Explanation of on_delete Parameters in models of Django

  • 2021-07-18 08:35:31
  • OfStack

In versions above Django 2.0, the on_delete parameter must be defined to create foreign keys and 1-to-1 relationships, and we can see the relevant information in its source code


class ForeignKey(ForeignObject):
  """
  Provide a many-to-one relation by adding a column to the local model
  to hold the remote value.

  By default ForeignKey will target the pk of the remote model but this
  behavior can be changed by using the ``to_field`` argument.
  """

  # Field flags
  many_to_many = False
  many_to_one = True
  one_to_many = False
  one_to_one = False

  rel_class = ManyToOneRel

  empty_strings_allowed = False
  default_error_messages = {
    'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
  }
  description = _("Foreign Key (type determined by related field)")

  def __init__(self, to, on_delete, related_name=None, related_query_name=None,
         limit_choices_to=None, parent_link=False, to_field=None,
         db_constraint=True, **kwargs):

to: Associated tables on_delete: When a piece of data in the table is deleted, the operation of associating foreign keys related_name: Reverse query parameter. After setting, you can reverse query the table where the foreign key is located in the associated table through this field. Default: set_ table name to_field: Default primary key, because mysql only supports primary key as foreign key, even if you do not explicitly create primary key, Django will automatically create it for you, if you are DB-first and do not create primary key: database default uses hidden field: DB_ROW_ID as primary key

on_delete Parameter Settings

CASCADE: Cascade delete, when the data in the associated table is deleted, the foreign key is also deleted

PROTECT: Protected mode. If this option is used, an ProtectedError error will be thrown when deleted.

SET_NULL: Set empty mode. When deleting, the foreign key field is set to empty, provided that blank=True, null=True. When defining this field, it is allowed to be empty.

SET_DEFAULT: Set the default value. When deleting, the foreign key field is set to the default value, so pay attention to adding 1 default value when defining foreign keys.

SET (): User-defined 1 value, which of course can only be the corresponding entity


Related articles: