Django的models中on_delete参数详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Django的models中on_delete参数详解

  2021-04-03 我要评论

在Django2.0以上的版本中,创建外键和一对一关系必须定义on_delete参数,我们可以在其源码中看到相关信息

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:关联的表
  • on_delete:当该表中的某条数据删除后,关联外键的操作
  • related_name:反查参数,设置后可以在被关联表中通过该字段反查外键所在表,默认:set_表名
  • to_field:默认主键,因为mysql只支持主键作为外键,就算你没显式的创建主键,Django会给你自动创建,如果你是DB-first,且没创建主键:数据库默认使用隐藏字段:DB_ROW_ID作为主键

on_delete参数设置

CASCADE:级联删除,当关联表中的数据删除时,该外键也删除

PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。

SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。

SET_DEFAULT: 设置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。

SET(): 自定义一个值,该值当然只能是对应的实体

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们