python

超轻量级php框架startmvc

Django的models中on_delete参数详解

更新时间:2020-07-15 01:36:01 作者:startmvc
在Django2.0以上的版本中,创建外键和一对一关系必须定义on_delete参数,我们可以在其源码中

在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(): 自定义一个值,该值当然只能是对应的实体

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

Django models on_delete参数